package com.hzeport.bgs22emduty.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.*;
import com.hzeport.bgs22emduty.dto.scheduleInfo.DutyScheduleInfoDownloadDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.*;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.outbound.db.DutyScheduleInfoRepositoryImpl;
import com.hzeport.bgs22emduty.service.BaseDeptInfoService;
import com.hzeport.bgs22emduty.service.DutyScheduleInfoService;
import com.hzeport.bgs22emduty.util.*;
import com.hzeport.bgs22emduty.vo.dutyScheduleInfo.*;
import com.hzeport.bgs22emduty.vo.dutydignInfo.DutyScheduleExcleVO;
import com.hzeport.bgs22emduty.vo.dutydignInfo.DutyScheduleInfoWordTabVO;
import com.hzeport.bgs22emduty.vo.dutydignInfo.DutyScheduleInfoWordVO;
import com.hzeport.bgs22emduty.common.base.BaseEntity;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.*;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2022-12-02 11:21:59
 */
@Service
@Slf4j
public class DutyScheduleInfoServiceImpl extends BaseServiceImpl<DutyScheduleInfoRepositoryImpl, DutyScheduleInfo> implements DutyScheduleInfoService {

    @Resource
    private DutyScheduleInfoRepository dutyScheduleInfoRepository;
    @Resource
    private DutyScheduleSetCustomRepository dutyScheduleSetCustomRepository;
    @Resource
    private ParamDutyRepository paramDutyRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private DutySignInfoRepository dutySignInfoRepository;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private BaseDeptInfoService baseDeptInfoService;
    @Resource
    private GuavacacheUtils guavacacheUtils;
    @Resource
    private ParamSubsidyRepository paramSubsidyRepository;
    @Resource
    private DutyScheduleSetCustomRecordRepository dutyScheduleSetCustomRecordRepository;

    @Resource
    private ParamLeaderRepository paramLeaderRepository;

    @Resource
    private ParamDictionaryRepository paramDictionaryRepository;

    @Resource
    private ScreenSubCustomRepository screenSubCustomRepository;

    @Resource
    private ScreenDutyMapsRepository screenDutyMapsRepository;

    @Resource
    private ParamHolidaysRepository paramHolidaysRepository;

    @Resource
    private BaseCustomPhoneRepositoy baseCustomPhoneRepositoy;
    @Resource
    private LoginCompoentService loginCompoentService;
    @Resource
    private ExportLogRepository exportLogRepository;

    @Override
    public String downloadWord(List<String> yearAndMonth, String type, UserInfoDetailVO userInfoDetailVO) throws Exception {
        if (!userInfoDetailVO.getRole().contains("ZGGLY")) {
            return doDownloadWord(yearAndMonth, type, userInfoDetailVO);
        } else {
            return doDownloadWordZG(yearAndMonth, type, userInfoDetailVO);
        }
    }

    private String doDownloadWordZG(List<String> yearAndMonth, String type, UserInfoDetailVO userInfoDetailVO) throws Exception {
        //todo
//        return "";
        if (CollectionUtils.isEmpty(yearAndMonth)) {
            throw new Exception("导出时间段不能为空!");
        }
//        LocalDate endDay = LocalDate.parse(yearAndMonth.get(1) + "-01").plusMonths(1).minusDays(1);
//        LocalDate day = LocalDate.parse(yearAndMonth.get(0) + "-01");
        LocalDate endDay = LocalDate.parse(yearAndMonth.get(1));
        LocalDate day = LocalDate.parse(yearAndMonth.get(0));
        List<ParamHolidays> paramHolidays = paramHolidaysRepository.list(new LambdaQueryWrapper<ParamHolidays>()
                .ge(ParamHolidays::getHolidayDate, day)
                .le(ParamHolidays::getHolidayDate, endDay).eq(ParamHolidays::getCustomId, userInfoDetailVO.getCustomscode())
                .in(ParamHolidays::getHolidayType, Arrays.asList(HolidaysEnum.HOLIDAY.getValue(), HolidaysEnum.IMPORTANT_PERIOD.getValue()))
                .orderByAsc(ParamHolidays::getHolidayDate));
//        if (!CollectionUtils.isEmpty(paramHolidays)) {
//            ParamHolidays lastDay = paramHolidays.get(paramHolidays.size() - 1);
////            if (lastDay.getHolidayDate() != null && DateUtil.isLastDayOfMonth(lastDay.getHolidayDate())) {
//////                paramHolidays = appendNextMonthHolidays(paramHolidays, day, endDay);
////            }
//        }
        String templateName = "总署排班模板.ftl";
        String fileUrl = systemConfig.getWordFileUrl() + UUID.randomUUID().toString() + ".doc";
        String templatePath = systemConfig.getTemplatePath();
        HashMap<String, Object> dataMap = new HashMap();
        String CJDeptName = paramDictionaryRepository.getOne(new LambdaQueryWrapper<ParamDictionary>()
                .eq(ParamDictionary::getParamCode, "ZSBM"), false).getParamName();
        List<String> customs = Arrays.asList(CJDeptName.split(","));
        List<BaseDeptInfo> baseDeptInfos = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                .in(BaseDeptInfo::getDeptName, customs));
        List<DutyScheduleInfo> dutyScheduleInfos;
        if (CollectionUtils.isEmpty(paramHolidays)) {
            dutyScheduleInfos = new ArrayList<>();
        } else {
            dutyScheduleInfos = dutyScheduleInfoRepository.list(new LambdaQueryWrapper<DutyScheduleInfo>()
                    .in(DutyScheduleInfo::getDDay, paramHolidays.stream().map(i -> i.getHolidayDate()).collect(Collectors.toList())));
        }
//        if (du)
//        List<ParamLeader> paramLeaders = paramLeaderRepository.list(new LambdaQueryWrapper<ParamLeader>()
//                .eq(ParamLeader::getLeaderName, "1"));
//        List<BasePersonInfo> basePersonInfos = guavacacheUtils.getPersons();
        Map<String, List<DutyScheduleInfo>> leaderMap = dutyScheduleInfos.stream().collect(Collectors.groupingBy(i -> i.getCustomId()));
        Map<String, BaseDeptInfo> dutyInfoMap = baseDeptInfos.stream().filter(i -> i.getDeptName() != null).filter(distinctByKey(i -> i.getDeptName())).collect(Collectors.toMap(i -> i.getDeptName(), i -> i));
        // 查询所有关区值班电话，形成以关区ID为key,电话号码为value的 map；如同一关区有多个电话号码，值以逗号拼接
        final List<BaseCustomPhone> dutyPhones = baseCustomPhoneRepositoy.list(new LambdaQueryWrapper<BaseCustomPhone>()
                .eq(BaseCustomPhone::getSType, STypeEnum.TYPE_ZMB.getCode())
                .eq(BaseCustomPhone::getSettingMode, SettingModeEnum.SETTINGS_PAGE.getCode()));
        final Map<String, String> customsPhonesMap = dutyPhones.stream().collect(Collectors.groupingBy(
                BaseCustomPhone::getCustomId, // 分组
                Collectors.mapping(BaseCustomPhone::getPhoneTel,
                        Collectors.collectingAndThen(Collectors.toSet(),    // 去重
                                phone -> String.join(" & ", phone))))); // 拼接
        for (int a = 0; a < customs.size(); a++) {
            String key = customs.get(a);
            BaseDeptInfo baseDeptInfo = dutyInfoMap.get(key);
            List<DutyScheduleInfoWordVO> lists = new ArrayList();
            if (baseDeptInfo != null && !CollectionUtils.isEmpty(paramHolidays)) {
                for (ParamHolidays temp : paramHolidays) {
                    DutyScheduleInfoWordVO today = new DutyScheduleInfoWordVO();
                    List<DutyScheduleInfo> paramLeader = leaderMap.get(baseDeptInfo.getId());
                    if (paramLeader == null) {
                        today.setDString(temp.getHolidayDate().getMonth().getValue() + "月" + temp.getHolidayDate().getDayOfMonth() + "日");
                        lists.add(today);
                        continue;
                    }
                    paramLeader = paramLeader.stream().filter(i -> "关领导".equals(i.getDUserjob()))
                            .collect(Collectors.toList());
                    Map<LocalDate, DutyScheduleInfo> dateDutyScheduleInfoMap =
                            paramLeader.stream().filter(i -> i.getDUsername() != null).filter(distinctByKey(i -> i.getDDay())).collect(Collectors.toMap(i -> i.getDDay(), i -> i));
                    DutyScheduleInfo basePersonInfo = null;
                    if (paramLeader != null) {
                        basePersonInfo = dateDutyScheduleInfoMap.get(temp.getHolidayDate());
                    }
                    if (basePersonInfo != null) {
                        today.setLeaderName(basePersonInfo.getDUsername());
                        today.setLeaderDutyPost(basePersonInfo.getLeadingPost());
                        today.setLeaderPhone(basePersonInfo.getDPhone());
                    }
                    today.setDString(temp.getHolidayDate().getMonth().getValue() + "月" + temp.getHolidayDate().getDayOfMonth() + "日");
                    lists.add(today);
//                    day = day.plusDays(1l);
                }
            }
            dataMap.put("project" + a, lists);
            if (null != baseDeptInfo) {
                dataMap.putIfAbsent("phone" + a, customsPhonesMap.getOrDefault(baseDeptInfo.getCustomId(), StringUtils.EMPTY));
            }
//            if (null != baseDeptInfo) {
//                final STypeEnum sTypeEnum = paramHolidaysRepository.deriveCurSType(baseDeptInfo.getCustomId(), day.atStartOfDay());
//                final BaseCustomPhone baseCustomPhone = baseCustomPhoneRepositoy.queryCurRecord(baseDeptInfo.getCustomId(),
//                        sTypeEnum.getCode(), day.atStartOfDay(), SettingModeEnum.SETTINGS_PAGE.getCode());
//                //加个判断，防止报错
//                if (Objects.nonNull(baseCustomPhone)) {
//                    dataMap.putIfAbsent("phone" + a, baseCustomPhone.getPhoneTel());
//                }else {
//                    dataMap.putIfAbsent("phone" + a, "");
//                }
//            }

        }
        WordUtils.generateWord(dataMap, templateName, fileUrl, templatePath);
        return fileUrl;
    }


    static <T> Predicate<T> distinctByKey(Function<? super T, ?> ketExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(ketExtractor.apply(t), Boolean.TRUE) == null;
    }

    private String doDownloadWord(List<String> yearAndMonth, String type, UserInfoDetailVO userInfoDetailVO) throws Exception {
        if (CollectionUtils.isEmpty(yearAndMonth)) {
            throw new Exception("导出时间段不能为空!");
        }

        String templateName = "排班模板.ftl";
        String fileUrl = systemConfig.getFileUrl() + File.separator + UUID.randomUUID().toString() + ".doc";
        String templatePath = systemConfig.getTemplatePath();

        log.info("==========templatePath:" + templatePath);

        // 查询所有关区值班电话，形成以关区ID为key,电话号码为value的 map；如同一关区有多个电话号码，值以逗号拼接
        final List<BaseCustomPhone> dutyPhones = baseCustomPhoneRepositoy.list(new LambdaQueryWrapper<BaseCustomPhone>()
                .eq(BaseCustomPhone::getSType, STypeEnum.TYPE_ZMB.getCode())
                        .eq(BaseCustomPhone::getCustomId,userInfoDetailVO.getCustomscode())
                .eq(BaseCustomPhone::getSettingMode, SettingModeEnum.SETTINGS_PAGE.getCode()));
        final Map<String, String> customsPhonesMap = dutyPhones.stream().collect(Collectors.groupingBy(
                BaseCustomPhone::getCustomId, // 分组
                Collectors.mapping(BaseCustomPhone::getPhoneTel,
                        Collectors.collectingAndThen(Collectors.toSet(),    // 去重
                                phone -> String.join(" & ", phone))))); // 拼接

        //双循环数据
        HashMap<String, Object> dataMap = new HashMap<>();
        List<DutyScheduleInfoWordTabVO> tabVOList = new ArrayList<>();

        ScreenDutyMaps mapsRepositoryOne = screenDutyMapsRepository.getOne(new LambdaQueryWrapper<ScreenDutyMaps>()
                .eq(ScreenDutyMaps::getCustomCode, userInfoDetailVO.getCustomscode()), false);

        DutyScheduleInfoWordTabVO dutyScheduleInfoWordTabVO1 = new DutyScheduleInfoWordTabVO();
        if (mapsRepositoryOne != null) {
            dutyScheduleInfoWordTabVO1.setFax(mapsRepositoryOne.getFax());
        }
        dutyScheduleInfoWordTabVO1.setPhone(customsPhonesMap.get(userInfoDetailVO.getCustomscode()));
        dutyScheduleInfoWordTabVO1.setCustomName(userInfoDetailVO.getCustomsName());
        dutyScheduleInfoWordTabVO1.setUserCustom(userInfoDetailVO.getCustomsName());
        List<ParamDuty> paramDutyList1 = paramDutyRepository.list(new LambdaQueryWrapper<ParamDuty>()
                .eq(ParamDuty::getDDept, userInfoDetailVO.getCustomscode())
                .orderByAsc(ParamDuty::getDType));
        StringBuilder attendedTime1 = new StringBuilder();
        for (ParamDuty duty : paramDutyList1) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
            String startTime = duty.getDStartTime().format(formatter);
            String endTime = duty.getDEndTime().format(formatter);
            attendedTime1.append("<w:tab/><w:tab/><w:t>").append(DTypeEnum.getDescByCode(duty.getDType())).append("：").append(startTime).append("-").append(endTime).append("<w:br/></w:t>");
        }
        dutyScheduleInfoWordTabVO1.setAttendedTime(attendedTime1.toString());

        List<DutyScheduleInfo> list = getDutyScheduleInfoList(yearAndMonth, type, userInfoDetailVO,"word");

        Map<LocalDate, List<DutyScheduleInfo>> dayListMap = list.stream().collect(Collectors.groupingBy(DutyScheduleInfo::getDDay));
        List<DutyScheduleInfoWordVO> lists = new ArrayList<>();
        dayListMap.forEach((k, v) -> {
            DutyScheduleInfoWordVO dutyScheduleInfoWordVO = new DutyScheduleInfoWordVO();
            LocalDate day = k;
            String dayOfWeek = DateUtil.getDaysOfWeek((long) day.getYear(), (long) day.getMonth().getValue(), day.getDayOfMonth());
            dutyScheduleInfoWordVO.setDString(k.getMonth().getValue() + "月" + k.getDayOfMonth() + "日\n(" + dayOfWeek + ")");
            List<DutyScheduleInfo> collect = v.stream().filter(info -> info.getDType() != null && info.getDUserjob() != null && info.getDutyTimesString() != null).collect(Collectors.toList());
            //带班
            List<DutyScheduleInfo> dbList = collect.stream().filter(i -> i.getDType() != null).filter(info -> info.getDType().equals("2")).collect(Collectors.toList());
            //值班
            List<DutyScheduleInfo> zbList = collect.stream().filter(i -> i.getDType() != null).filter(info -> info.getDType().equals("1")).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(dbList)) {
                List<DutyScheduleInfo> gldList = dbList.stream().filter(i -> "关领导".equals(i.getDUserjob()) && !StringUtils.isEmpty(i.getDUsername()))
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(gldList)) {
                    dutyScheduleInfoWordVO.setLeaderName(gldList.get(0).getDUsername());
                }
            }
            List<DutyScheduleInfo> zb = dbList.stream().filter(i -> i.getDUserjob() != null).filter(info -> info.getDUserjob().equals("处领导") && info.getDutyTimesString().startsWith("白天")).collect(Collectors.toList());
            List<DutyScheduleInfo> zw = dbList.stream().filter(i -> i.getDUserjob() != null).filter(info -> info.getDUserjob().equals("处领导") && info.getDutyTimesString().startsWith("夜间")).collect(Collectors.toList());
            List<DutyScheduleInfo> kb = zbList.stream().filter(i -> i.getDUserjob() != null).filter(info -> info.getDUserjob().equals("科领导") && info.getDutyTimesString().startsWith("白天")).collect(Collectors.toList());
            List<DutyScheduleInfo> kw = zbList.stream().filter(i -> i.getDUserjob() != null).filter(info -> info.getDUserjob().equals("科领导") && info.getDutyTimesString().startsWith("夜间")).collect(Collectors.toList());
            if (zb.size() > 0) {
                dutyScheduleInfoWordVO.setCBdeptName(zb.get(0).getDDeptname());
                dutyScheduleInfoWordVO.setCBpersonName(zb.get(0).getDUsername());
                dutyScheduleInfoWordVO.setCBpersonNo(zb.get(0).getPhoneShort());
            }
            if (zw.size() > 0) {
                dutyScheduleInfoWordVO.setCHdeptName(zw.get(0).getDDeptname());
                dutyScheduleInfoWordVO.setCHpersonName(zw.get(0).getDUsername());
                dutyScheduleInfoWordVO.setCHpersonNo(zw.get(0).getPhoneShort());
            }
            if (kb.size() > 0) {
                dutyScheduleInfoWordVO.setKBdeptName(kb.get(0).getDDeptname());
                dutyScheduleInfoWordVO.setKBpersonName(kb.get(0).getDUsername());
                dutyScheduleInfoWordVO.setKBpersonNo(kb.get(0).getPhoneShort());
            }
            if (kw.size() > 0) {
                dutyScheduleInfoWordVO.setKHdeptName(kw.get(0).getDDeptname());
                dutyScheduleInfoWordVO.setKHpersonName(kw.get(0).getDUsername());
                dutyScheduleInfoWordVO.setKHpersonNo(kw.get(0).getPhoneShort());
            }
            dutyScheduleInfoWordVO.setDay(k);
            lists.add(dutyScheduleInfoWordVO);
        });
        List<DutyScheduleInfoWordVO> temps = lists.stream().sorted(Comparator.comparing(a -> a.getDay())).collect(Collectors.toList());
        dutyScheduleInfoWordTabVO1.setProject(temps);
//        dutyScheduleInfoWordTabVO1.setYear(LocalDate.parse(yearAndMonth.get(0) + "-01").getYear());
        dutyScheduleInfoWordTabVO1.setYear(LocalDate.parse(yearAndMonth.get(0)).getYear());
        tabVOList.add(dutyScheduleInfoWordTabVO1);

        //直属关的隶属关
        List<ScreenSubCustom> screenSubCustoms = screenSubCustomRepository.list(new LambdaQueryWrapper<ScreenSubCustom>()
                .eq(ScreenSubCustom::getParentid, userInfoDetailVO.getCustomscode()));

        for (ScreenSubCustom screenSubCustom : screenSubCustoms) {
            DutyScheduleInfoWordTabVO dutyScheduleInfoWordTabVO = new DutyScheduleInfoWordTabVO();
            dutyScheduleInfoWordTabVO.setUserCustom(userInfoDetailVO.getCustomsName());
            dutyScheduleInfoWordTabVO.setFax(screenSubCustom.getFax());
            dutyScheduleInfoWordTabVO.setPhone(screenSubCustom.getPhone());
            dutyScheduleInfoWordTabVO.setCustomName(screenSubCustom.getDeptName());
            List<ParamDuty> paramDutyList = paramDutyRepository.list(new LambdaQueryWrapper<ParamDuty>()
                    .eq(ParamDuty::getDDept, screenSubCustom.getId())
                    .orderByAsc(ParamDuty::getDType));
            StringBuilder attendedTime = new StringBuilder();
            for (ParamDuty duty : paramDutyList) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
                String startTime = duty.getDStartTime().format(formatter);
                String endTime = duty.getDEndTime().format(formatter);
                attendedTime.append("<w:tab/><w:tab/><w:t>").append(DTypeEnum.getDescByCode(duty.getDType())).append("：").append(startTime).append("-").append(endTime).append("<w:br/></w:t>");
            }
            dutyScheduleInfoWordTabVO.setAttendedTime(attendedTime.toString());
//            DutyScheduleInfo dutyScheduleInfo = dutyScheduleInfoRepository.getOne(new LambdaQueryWrapper<DutyScheduleInfo>()
//                    .eq(DutyScheduleInfo::getCustomId, screenSubCustom.getId()));


            List<BaseDeptInfo> baseDeptInfos = baseDeptInfoRepository.list(new LambdaQueryWrapper<BaseDeptInfo>()
                    .in(BaseDeptInfo::getDeptName, screenSubCustom.getDeptName()));

            //获取关领导
//            List<ParamLeader> paramLeaders = paramLeaderRepository.list(new LambdaQueryWrapper<ParamLeader>()
//                    .eq(ParamLeader::getLeaderName, "1"));
//            List<BasePersonInfo> basePersonInfos = guavacacheUtils.getPersons();
//            Map<String, ParamLeader> leaderMap = paramLeaders.stream().filter(distinctByKey(i -> i.getDeptId())).collect(Collectors.toMap(i -> i.getDeptId(), i -> i));
//            Map<String, BasePersonInfo> basePersonInfoMaps = basePersonInfos.stream().filter(distinctByKey(i -> i.getUserno())).collect(Collectors.toMap(i -> i.getUserno(), i -> i));
            Map<String, BaseDeptInfo> dutyInfoMap = baseDeptInfos.stream().filter(i -> i.getDeptName() != null).filter(distinctByKey(i -> i.getDeptName())).collect(Collectors.toMap(i -> i.getDeptName(), i -> i));

            BaseDeptInfo baseDeptInfo = dutyInfoMap.get(screenSubCustom.getDeptName());
            List<DutyScheduleInfoWordVO> lists1 = new ArrayList<>();
//            if (baseDeptInfo != null) {
//                LocalDate endDay = LocalDate.parse(yearAndMonth.get(1) + "-01").plusMonths(1).minusDays(1);
//                LocalDate day = LocalDate.parse(yearAndMonth.get(0) + "-01");
            LocalDate endDay = LocalDate.parse(yearAndMonth.get(1)).minusDays(1);
            LocalDate day = LocalDate.parse(yearAndMonth.get(0)).minusDays(1);
            while (day.compareTo(endDay) <= 0) {
                day = day.plusDays(1l);
                List<ParamHolidays> paramHolidays = paramHolidaysRepository.list(new LambdaQueryWrapper<ParamHolidays>()
                        .ge(ParamHolidays::getHolidayDate, day)
                        .le(ParamHolidays::getHolidayDate, endDay)
                        .eq(ParamHolidays::getCustomId, userInfoDetailVO.getCustomscode())
                        .in(ParamHolidays::getHolidayType, Arrays.asList(HolidaysEnum.HOLIDAY.getValue(), HolidaysEnum.IMPORTANT_PERIOD.getValue()))
                        .orderByAsc(ParamHolidays::getHolidayDate));
                if (!paramHolidays.stream().map(i -> i.getHolidayDate()).collect(Collectors.toList())
                        .contains(day)) {
                    continue;
                }
//                    ParamLeader paramLeader = leaderMap.get(baseDeptInfo.getId());
//                    BasePersonInfo basePersonInfo = null;
//                    if (paramLeader != null) {
//                        basePersonInfo = basePersonInfoMaps.get(paramLeader.getLeaderCode());
//                    }
                DutyScheduleInfoWordVO today = new DutyScheduleInfoWordVO();
//                    if (basePersonInfo != null) {
//                        today.setLeaderName(basePersonInfo.getUsername());
//                        today.setLeaderDutyPost(basePersonInfo.getDutypost());
//                        today.setLeaderPhone(basePersonInfo.getPhone());
//                    }
                String dayOfWeek = DateUtil.getDaysOfWeek((long) day.getYear(), (long) day.getMonth().getValue(), day.getDayOfMonth());
                today.setDString(day.getMonth().getValue() + "月" + day.getDayOfMonth() + "日" + "\n(" + dayOfWeek + ")");
                lists1.add(today);
            }
//            }
            dutyScheduleInfoWordTabVO.setProject(lists1);
//            dutyScheduleInfoWordTabVO.setYear(LocalDate.parse(yearAndMonth.get(0) + "-01").getYear());
            dutyScheduleInfoWordTabVO.setYear(LocalDate.parse(yearAndMonth.get(0)).getYear());
            tabVOList.add(dutyScheduleInfoWordTabVO);
        }
        dataMap.put("tabList", tabVOList);

        WordUtils.generateWord(dataMap, templateName, fileUrl, templatePath);
        return fileUrl;
    }

    private void getParentDeptOnlyCJFor(List<DutyScheduleInfo> list) {
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> deptInfoMap = deptInfoList.stream().collect(Collectors.toMap(BaseDeptInfo::getId, i -> i));
        for (DutyScheduleInfo dutyScheduleInfo : list) {
            BaseDeptInfo baseDeptInfo = deptInfoMap.get(dutyScheduleInfo.getDDept());
            if (baseDeptInfo != null) {
                BaseDeptInfo parent = deptInfoMap.get(baseDeptInfo.getParentid());
                if (parent != null && !systemConfig.getZsCustomName().equals(parent.getDeptName())) {
                    dutyScheduleInfo.setDDeptname(parent.getDeptName());
                }
            }
            if ("科员".equals(dutyScheduleInfo.getDUserjob()) || "科领导".equals(dutyScheduleInfo.getDUserjob())) {
                dutyScheduleInfo.setDType("1");
            } else if ("处领导".equals(dutyScheduleInfo.getDUserjob()) || "关领导".equals(dutyScheduleInfo.getDUserjob())) {
                dutyScheduleInfo.setDType("2");
            }
        }
    }

    private void getParentDeptOnlyCJForWord(List<DutyScheduleInfo> list) {
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> deptInfoMap = deptInfoList.stream().collect(Collectors.toMap(BaseDeptInfo::getId, i -> i));
        getParentDeptFor(list, deptInfoMap);
//        for (DutyScheduleInfo dutyScheduleInfo : list) {
//            BaseDeptInfo baseDeptInfo = deptInfoMap.get(dutyScheduleInfo.getDDept());
//            if (baseDeptInfo != null) {
//                BaseDeptInfo parent = deptInfoMap.get(baseDeptInfo.getParentid());
//                if (parent != null && !systemConfig.getZsCustomName().equals(parent.getDeptName())) {
//                    dutyScheduleInfo.setDDeptname(parent.getDeptName());
//                }
//            }
////            if ("科员".equals(dutyScheduleInfo.getDUserjob()) || "科领导".equals(dutyScheduleInfo.getDUserjob())) {
////                dutyScheduleInfo.setDType("1");
////            } else if ("处领导".equals(dutyScheduleInfo.getDUserjob()) || "关领导".equals(dutyScheduleInfo.getDUserjob())) {
////                dutyScheduleInfo.setDType("2");
////            }
//        }
    }

    @Override
    public List<DutyScheduleExcleVO> downloadExcel(DutyScheduleInfoDownloadDTO dutyScheduleInfoDownloadDTO, UserInfoDetailVO userInfoDetailVO) throws Exception {
        List<DutyScheduleInfo> list = getDutyScheduleInfoList(dutyScheduleInfoDownloadDTO.getYearAndMonth(), dutyScheduleInfoDownloadDTO.getType(), userInfoDetailVO,"excel");

        UserInfoDetailVO user = loginCompoentService.getUserInfo();
        //查询需写入日志
        ExportLog exportLog = new ExportLog();
        exportLog.setReqPath("/dutyscheduleinfo/getlistPage");
        exportLog.setDataRange(com.alibaba.fastjson.JSONObject.toJSONString(dutyScheduleInfoDownloadDTO));
        exportLog.setFileInfo(com.alibaba.fastjson.JSONObject.toJSONString(dutyScheduleInfoDownloadDTO));
        exportLog.setOperateType(ActionTypeEnum.EXPORT.getCode());
        exportLog.setOperatorCode(user.getPersonId());
        exportLogRepository.save(exportLog);
        if (list.size() > 10000) {

            log.error("导出条数超过10000");
        }
        if (!CollectionUtils.isEmpty(list)) {
            getParentDeptOnlyCJForWord(list);
        }
        List<DutyScheduleExcleVO> dutyScheduleExcleVOS = list.stream().map(dutyScheduleInf -> {
            DutyScheduleExcleVO dutyScheduleExcleVO = new DutyScheduleExcleVO();
            BeanUtils.copyProperties(dutyScheduleInf, dutyScheduleExcleVO);

            dutyScheduleExcleVO.setDDayString(dutyScheduleInf.getDDay().toString());
            return dutyScheduleExcleVO;
        }).collect(Collectors.toList());
        dutyScheduleExcleVOS.forEach(dutyScheduleExcleVO -> {
            if ("1".equals(dutyScheduleExcleVO.getSType())) {
                dutyScheduleExcleVO.setSType("工作日班");
            }
            if ("2".equals(dutyScheduleExcleVO.getSType())) {
                dutyScheduleExcleVO.setSType("节假日班");
            }
            if ("3".equals(dutyScheduleExcleVO.getSType())) {
                dutyScheduleExcleVO.setSType("重要时期班");
            }
            if ("4".equals(dutyScheduleExcleVO.getSType())) {
                dutyScheduleExcleVO.setSType("周末班");
            }
            if ("1".equals(dutyScheduleExcleVO.getDType())) {
                dutyScheduleExcleVO.setDType("值班");
            }
            if ("2".equals(dutyScheduleExcleVO.getDType())) {
                dutyScheduleExcleVO.setDType("带班");
            }

        });

        return dutyScheduleExcleVOS;
    }

    @Override
    public Object getDutyScheduleInfoPage(DutyScheduleInfoListVO dutyScheduleInfo, UserInfoDetailVO userInfoDetailVO) throws Exception {
        List<DutyScheduleInfo> dutyScheduleInfos = getDutyScheduleInfoList(dutyScheduleInfo, userInfoDetailVO);
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> deptInfoMap = deptInfoList.stream().collect(Collectors.toMap(BaseDeptInfo::getId, i -> i));
        if (!CollectionUtils.isEmpty(dutyScheduleInfos)) {
            getParentDeptFor(dutyScheduleInfos, deptInfoMap);
        }
        List<DutyScheduleInfo> records = dutyScheduleInfos.stream().sorted(Comparator.comparing(DutyScheduleInfo::getDDay).thenComparing(DutyScheduleInfo::getDStartDateTime, (o1, o2) -> {
            return o1.compareTo(o2);
        })).collect(Collectors.toList());
        List<DutyScheduleInfo> leaders = records;
//        List<DutyScheduleInfo> members=records.stream().filter(i->!"2".equals(i.getDType())).sorted(Comparator.comparing(DutyScheduleInfo::getDDay)).collect(Collectors.toList());
//        leaders.addAll(members);
        Page<DutyScheduleInfo> pageResult = new Page<>();
        pageResult.setTotal(records.size());
        int start = (dutyScheduleInfo.getPageNum() - 1) * dutyScheduleInfo.getPageSize();
        int end = start + dutyScheduleInfo.getPageSize();
        if (end > records.size()) {
            end = records.size();
        }
        leaders = leaders.subList(start, end);
        pageResult.setRecords(leaders);
        return pageResult;
    }

    private void getParentDeptFor(List<DutyScheduleInfo> dutyScheduleInfos, Map<String, BaseDeptInfo> deptInfoMap) {

        for (DutyScheduleInfo dutyScheduleInfo : dutyScheduleInfos) {
            BaseDeptInfo baseDeptInfo = deptInfoMap.get(dutyScheduleInfo.getDDept());
            if (baseDeptInfo != null) {
                BaseDeptInfo parent = deptInfoMap.get(baseDeptInfo.getParentid());
                if (parent != null && !systemConfig.getZsCustomName().equals(parent.getDeptName())
                        && !StringUtils.isEmpty(parent.getDeptName()) && !parent.getDeptName().contains("海关")) {
                    dutyScheduleInfo.setDDeptname(dutyScheduleInfo.getDDeptname() + "(" + parent.getDeptName() + ")");
                }
            }

        }
    }

    private List<DutyScheduleInfo> getDutyScheduleInfoList(List<String> yearAndMonth, String type, UserInfoDetailVO userInfoDetailVO, String exportType) throws Exception {
        //TODO


        //        DutyScheduleInfoListVO dutyScheduleInfo = new DutyScheduleInfoListVO();
//        dutyScheduleInfo.setSType(type);
//        DutyScheduleInfoDTO dutyScheduleInfoDTO=new DutyScheduleInfoDTO();
//        dutyScheduleInfoDTO.setTime(yearAndMonth);
//        dutyScheduleInfoDTO.setDDept(userInfoDetailVO.getDeptId());
        LambdaQueryWrapper<DutyScheduleInfo> lambdaQueryWrappe = new LambdaQueryWrapper<DutyScheduleInfo>()
                .ge(DutyScheduleInfo::getDDay, LocalDate.parse(yearAndMonth.get(0))).
                le(DutyScheduleInfo::getDDay, LocalDate.parse(yearAndMonth.get(1)));
//                .ge(DutyScheduleInfo::getDDay, LocalDate.parse(yearAndMonth.get(0) + "-01")).
//                        lt(DutyScheduleInfo::getDDay, LocalDate.parse(yearAndMonth.get(1) + "-01").plusMonths(1).minusDays(1));
        if (!StringUtils.isEmpty(type)) {
            lambdaQueryWrappe.eq(DutyScheduleInfo::getSType, type);
        }
        if (!userInfoDetailVO.getRole().contains("ZGGLY")) {
            lambdaQueryWrappe.eq(DutyScheduleInfo::getCustomId, userInfoDetailVO.getCustomscode());
        }
        //如果是导出word其实要拿所有数据，导出excel就免了
        if (userInfoDetailVO.getRole().contains("ZGGLY")&&"excel".equals(exportType)){
            lambdaQueryWrappe.eq(DutyScheduleInfo::getCustomId, userInfoDetailVO.getCustomscode());
        }
        lambdaQueryWrappe.orderByDesc(DutyScheduleInfo::getDDay);
        lambdaQueryWrappe.orderByAsc(DutyScheduleInfo::getDutyTimesString);
        return repository.list(lambdaQueryWrappe);
    }

    private List<DutyScheduleInfo> getAllDutyScheduleInfoList(DutyScheduleInfoListVO dutyScheduleInfo) throws Exception {
        String[] tempArray = dutyScheduleInfo.getMonth().split("-");
        Long yearLong = Long.valueOf(tempArray[0]);
        Long monthLong = Long.valueOf(tempArray[1]);
        LambdaQueryWrapper<DutyScheduleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(DutyScheduleInfo::getDDay, LocalDate.of((int) (long) yearLong, (int) (long) monthLong, 1))
                .le(DutyScheduleInfo::getDDay, LocalDate.of((int) (long) yearLong, (int) (long) monthLong, 1).plusMonths(1).minusDays(1));
        if (!StringUtils.isEmpty(dutyScheduleInfo.getSType())) {
            lambdaQueryWrapper.eq(DutyScheduleInfo::getSType, dutyScheduleInfo.getSType());
        }
        lambdaQueryWrapper.orderByAsc(DutyScheduleInfo::getSType, DutyScheduleInfo::getDDay, DutyScheduleInfo::getDDayString, DutyScheduleInfo::getDStartDateTime, DutyScheduleInfo::getDUserjob);
        return dutyScheduleInfoRepository.list(lambdaQueryWrapper);
    }

    private List<DutyScheduleInfo> getDutyScheduleInfoList(DutyScheduleInfoListVO dutyScheduleInfo, UserInfoDetailVO userInfoDetailVO) throws Exception {
        if (userInfoDetailVO.getRole() != null && (userInfoDetailVO.getRole().contains("SCHEDULE_CJ_MGR"))) {
            if (userInfoDetailVO.getDeptId() == null) {
                throw new Exception("无法匹配用户" + userInfoDetailVO.getCustomscode() + "与其应管辖的部门");
            }
            BaseDeptInfo father = baseDeptInfoRepository.getById(userInfoDetailVO.getDeptId());
            List<BaseDeptInfo> childern = new ArrayList<>();
            childern.add(father);
            List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
            baseDeptInfoService.getChild(father, childern, deptInfoList);
            LambdaQueryWrapper<DutyScheduleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(DutyScheduleInfo::getDDept, childern.stream().map(BaseDeptInfo::getId).collect(Collectors.toList()));
            List<LocalDate> betweenTimes = DateUtil.getDatesForAQuater(dutyScheduleInfo.getYear(), dutyScheduleInfo.getQuarter());
            lambdaQueryWrapper.ge(DutyScheduleInfo::getDDay, betweenTimes.get(0));
            lambdaQueryWrapper.le(DutyScheduleInfo::getDDay, betweenTimes.get(1));
            if (!StringUtils.isEmpty(dutyScheduleInfo.getSType())) {
                lambdaQueryWrapper.eq(DutyScheduleInfo::getSType, dutyScheduleInfo.getSType());
            }
            lambdaQueryWrapper.orderByAsc(DutyScheduleInfo::getSType, DutyScheduleInfo::getDDay, DutyScheduleInfo::getDDayString, DutyScheduleInfo::getDStartDateTime, DutyScheduleInfo::getDUserjob);
            return dutyScheduleInfoRepository.list(lambdaQueryWrapper);
        } else {
            String[] tempArray = dutyScheduleInfo.getMonth().split("-");
            Long yearLong = Long.valueOf(tempArray[0]);
            Long monthLong = Long.valueOf(tempArray[1]);
            DutyScheduleSetCustom dutyScheduleSetCustom = dutyScheduleSetCustomRepository.getOne(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                    .le(DutyScheduleSetCustom::getSYearStart, yearLong)
                    .ge(DutyScheduleSetCustom::getSYearEnd, yearLong)
                    .le(DutyScheduleSetCustom::getSMonthStart, monthLong)
                    .ge(DutyScheduleSetCustom::getSMonthEnd, monthLong)
                    .eq(DutyScheduleSetCustom::getCustomId, userInfoDetailVO.getCustomscode())
                    .eq(DutyScheduleSetCustom::getSStatus, SStatusEnum.TYPE_SUBMIT.getValue()));
            if (dutyScheduleSetCustom == null) {
                throw new Exception("未初始化此关区此年份的排班规划！");
            }
            LambdaQueryWrapper<DutyScheduleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DutyScheduleInfo::getSetCustomId, dutyScheduleSetCustom.getId());
            if (!StringUtils.isEmpty(dutyScheduleInfo.getSType())) {
                lambdaQueryWrapper.eq(DutyScheduleInfo::getSType, dutyScheduleInfo.getSType());
            }
            lambdaQueryWrapper.ge(DutyScheduleInfo::getDDay, LocalDate.of((int) (long) yearLong, (int) (long) monthLong, 1))
                    .le(DutyScheduleInfo::getDDay, LocalDate.of((int) (long) yearLong, (int) (long) monthLong, 1).plusMonths(1).minusDays(1));
            lambdaQueryWrapper.orderByAsc(DutyScheduleInfo::getDDay, DutyScheduleInfo::getSType, DutyScheduleInfo::getDStartDateTime, DutyScheduleInfo::getDUserjob);
            return dutyScheduleInfoRepository.list(lambdaQueryWrapper);
        }

    }

    public Integer getCode(String subString) {
        switch (subString) {
            case "上午":
                return 1;
            case "下午":
                return 2;
            case "夜间":
                return 3;
            case "全天":
                return 4;
            case "其他":
                return 5;
            case "白天":
                return 6;
        }
        return 0;
    }

    @Override
    public BaseResult<Page<DutyScheduleInfoVO>> getlistPage(DutyScheduleInfoDTO dutyScheduleInfo, UserInfoDetailVO userInfoDetailVO) {
        UserInfoDetailVO user = loginCompoentService.getUserInfo();
        //查询需写入日志
        ExportLog exportLog = new ExportLog();
        exportLog.setReqPath("/dutyscheduleinfo/getlistPage");
        exportLog.setDataRange(com.alibaba.fastjson.JSONObject.toJSONString(dutyScheduleInfo));
        exportLog.setFileInfo(com.alibaba.fastjson.JSONObject.toJSONString(dutyScheduleInfo));
        exportLog.setOperateType(ActionTypeEnum.SEL.getCode());
        exportLog.setOperatorCode(user.getPersonId());
        exportLogRepository.save(exportLog);
        LambdaQueryWrapper<DutyScheduleInfo> Wrapper = new LambdaQueryWrapper<>();
        if (!CollectionUtils.isEmpty(dutyScheduleInfo.getTime()) && dutyScheduleInfo.getTime().get(0) != null) {
            Wrapper.ge(DutyScheduleInfo::getDDay, LocalDate.parse(dutyScheduleInfo.getTime().get(0)));
        }
        if (!CollectionUtils.isEmpty(dutyScheduleInfo.getTime()) && dutyScheduleInfo.getTime().get(1) != null) {
            Wrapper.le(DutyScheduleInfo::getDDay, LocalDate.parse(dutyScheduleInfo.getTime().get(1)));
        }
        if (!StringUtils.isEmpty(dutyScheduleInfo.getSType())) {
            Wrapper.eq(DutyScheduleInfo::getSType, dutyScheduleInfo.getSType());
        }
        Wrapper.eq(DutyScheduleInfo::getCustomId, userInfoDetailVO.getCustomscode());
        if (!StringUtils.isEmpty(dutyScheduleInfo.getDDept())) {
            BaseDeptInfo father = baseDeptInfoRepository.getById(dutyScheduleInfo.getDDept());
            List<BaseDeptInfo> childern = new ArrayList<>();
            childern.add(father);
            List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
            baseDeptInfoService.getChild(father, childern, deptInfoList);
            if (!CollectionUtils.isEmpty(childern)) {
                Wrapper.in(DutyScheduleInfo::getDDept, childern.stream().map(BaseDeptInfo::getId).collect(Collectors.toList()));
            } else {
                return BaseResult.ok(new Page<>(), "查询成功");
            }
        }
        if (!StringUtils.isEmpty(dutyScheduleInfo.getDUsername())) {
            Wrapper.eq(DutyScheduleInfo::getDUsername, dutyScheduleInfo.getDUsername());
        }
        Wrapper.eq(BaseEntity::getDelFlag, DeleteFlagEnum.NOT_DELETE.getValue());
//        Wrapper.orderByDesc(DutyScheduleInfo::getDDay);
//        Wrapper.orderDutyScheduleInfo::get);
//        Wrapper.orderByAsc(DutyScheduleInfo::getDutyType);
        Wrapper.last(" order by DUTY_DAY desc,duty_param_type asc,DUTY_TYPE asc");
        Page page1 = new Page();
        page1.setCurrent(ObjectUtils.isNotEmpty(dutyScheduleInfo.getPageNum()) ? dutyScheduleInfo.getPageNum() : 1);
        page1.setSize(ObjectUtils.isNotEmpty(dutyScheduleInfo.getPageSize()) ? dutyScheduleInfo.getPageSize() : 99999);
        Page<DutyScheduleInfo> page = dutyScheduleInfoRepository.page(page1, Wrapper);
        List<DutyScheduleInfoVO> dutyScheduleInfoVOS = new ArrayList<>();
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> deptInfoMap = deptInfoList.stream().collect(Collectors.toMap(BaseDeptInfo::getId, i -> i));
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            getParentDeptFor(page.getRecords(), deptInfoMap);
        }
        for (DutyScheduleInfo scheduleInfo : page.getRecords()) {
            DutyScheduleInfoVO dutyScheduleInfoVO = new DutyScheduleInfoVO();
            BeanUtils.copyProperties(scheduleInfo, dutyScheduleInfoVO);
            dutyScheduleInfoVO.setId(scheduleInfo.getId());
            dutyScheduleInfoVO.setDPhone(scheduleInfo.getDPhone());
            dutyScheduleInfoVO.setDPhoneLand(scheduleInfo.getDPhoneLand());
            dutyScheduleInfoVO.setDutypost(scheduleInfo.getDUserjob());
            dutyScheduleInfoVO.setTime(scheduleInfo.getDutyTimesString());
            dutyScheduleInfoVO.setDUserno(scheduleInfo.getDUserno());
            dutyScheduleInfoVO.setDDeptname(scheduleInfo.getDDeptname());
            dutyScheduleInfoVO.setDUsername(scheduleInfo.getDUsername());
            dutyScheduleInfoVO.setDOperatorName(scheduleInfo.getDOperatorName());
            dutyScheduleInfoVO.setDExchangerName(scheduleInfo.getDExchangerName());
            if (scheduleInfo.getDDay() == null) {
                dutyScheduleInfoVO.setDDay(scheduleInfo.getDDayString());
            } else {
                dutyScheduleInfoVO.setDDay(String.valueOf(scheduleInfo.getDDay()));
            }
            ParamDuty paramDuty = guavacacheUtils.getParamDuty(scheduleInfo.getDutyTimesId());
            if (paramDuty != null && !StringUtils.isEmpty(paramDuty.getId())) {
                DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm:ss");
                dutyScheduleInfoVO.setTime(paramDuty.getDStartTime().format(format) + "-" + paramDuty.getDEndTime().format(format));
                dutyScheduleInfoVO.setTime(DTypeEnum.TYPE_DAY_TIME.getValueByCode(paramDuty.getDType()) + "(" + dutyScheduleInfoVO.getTime() + ")");
            }
            dutyScheduleInfoVOS.add(dutyScheduleInfoVO);
        }
        Page<DutyScheduleInfoVO> voPage = new Page<>();
        voPage.setRecords(dutyScheduleInfoVOS);
        voPage.setTotal(page.getTotal());
        return BaseResult.ok(voPage, "查询成功");
    }

    @Override
    public BaseResult<Page<DutyScheduleinfoMoneyVO>> moneylist(MoneylistDTO moneylistDTO, UserInfoDetailVO userInfoDetailVO) {
        LambdaQueryWrapper<DutyScheduleInfo> Wrapper = new LambdaQueryWrapper<>();
        if (!CollectionUtils.isEmpty(moneylistDTO.getDDay()) && moneylistDTO.getDDay().get(0) != null) {
            Wrapper.ge(DutyScheduleInfo::getDDay, LocalDate.parse(moneylistDTO.getDDay().get(0)));
        }
        if (!CollectionUtils.isEmpty(moneylistDTO.getDDay()) && moneylistDTO.getDDay().get(1) != null) {
            Wrapper.le(DutyScheduleInfo::getDDay, LocalDate.parse(moneylistDTO.getDDay().get(1)));
        }
        if (!StringUtils.isEmpty(moneylistDTO.getDDept())) {
            Wrapper.eq(DutyScheduleInfo::getDDept, moneylistDTO.getDDept());
        }
        Wrapper.eq(DutyScheduleInfo::getCustomId, userInfoDetailVO.getCustomscode());
        if (!StringUtils.isEmpty(moneylistDTO.getDUsername())) {
            Wrapper.eq(DutyScheduleInfo::getDUsername, moneylistDTO.getDUsername());
        }
        Wrapper.eq(BaseEntity::getDelFlag, DeleteFlagEnum.NOT_DELETE.getValue());
        Wrapper.eq(DutyScheduleInfo::getIsDraw, "1");
        Wrapper.le(DutyScheduleInfo::getDDay, LocalDateTime.now());
        Wrapper.isNotNull(DutyScheduleInfo::getDUserno).isNotNull(DutyScheduleInfo::getDUsername);
        Wrapper.orderByDesc(DutyScheduleInfo::getDDay).orderByAsc(DutyScheduleInfo::getDUsername);
        Page<DutyScheduleInfo> page = dutyScheduleInfoRepository.page(new Page(moneylistDTO.getPageNum(), moneylistDTO.getPageSize()), Wrapper);
        List<DutyScheduleinfoMoneyVO> moneyVOList = new ArrayList<>();
        for (DutyScheduleInfo scheduleInfo : page.getRecords()) {
            DutyScheduleinfoMoneyVO scheduleinfoMoneyVO = new DutyScheduleinfoMoneyVO();
            MoneyVO moneyVO = getdutyTimesString(scheduleInfo);
            BeanUtils.copyProperties(scheduleInfo, scheduleinfoMoneyVO);
            if (moneyVO != null) {
                BeanUtils.copyProperties(moneyVO, scheduleinfoMoneyVO);
            }
            //已支取
            if (!StringUtils.isEmpty(scheduleInfo.getIsDraw()) && "0".equals(scheduleInfo.getIsDraw())) {
                scheduleinfoMoneyVO.setIsRest("0");
            } else if (!StringUtils.isEmpty(scheduleInfo.getIsDraw())) {
                scheduleinfoMoneyVO.setIsRest("1");
            }
            scheduleinfoMoneyVO.setDDay(String.valueOf(scheduleInfo.getDDay()));
            moneyVOList.add(scheduleinfoMoneyVO);
        }
        Page<DutyScheduleinfoMoneyVO> voPage = new Page<>();
        voPage.setRecords(moneyVOList);
        voPage.setTotal(page.getTotal());
        return BaseResult.ok(voPage, "查询成功");
    }

    @Override
    public String exportmoney(MoneylistDTO moneylistDTO, UserInfoDetailVO userInfoDetailVO) {
        List<DutyScheduleinfoMoneyVO> dutyScheduleinfoMoneyVOS = null;
        moneylistDTO.setPageNum(1);
        moneylistDTO.setPageSize(9999);
        Page<DutyScheduleinfoMoneyVO> moneylist = moneylist(moneylistDTO, userInfoDetailVO).getData();
        dutyScheduleinfoMoneyVOS = moneylist.getRecords();
        //导出集合赋值
        List<DutyScheduleInfoMoneyExcelVO> wxpParamDictionaryExcelVOS = dutyScheduleinfoMoneyVOS.stream().map(i -> {
            DutyScheduleInfoMoneyExcelVO dutyScheduleInfoMoneyExcelVO = new DutyScheduleInfoMoneyExcelVO();
            BeanUtils.copyProperties(i, dutyScheduleInfoMoneyExcelVO);
            //已支取
            if (!StringUtils.isEmpty(i.getIsDraw()) && "0".equals(i.getIsDraw())) {
                dutyScheduleInfoMoneyExcelVO.setIsevening("是");
                dutyScheduleInfoMoneyExcelVO.setIsrest("否");
            } else if (!StringUtils.isEmpty(i.getIsDraw())) {
                dutyScheduleInfoMoneyExcelVO.setIsevening("否");
                dutyScheduleInfoMoneyExcelVO.setIsrest("是");

            }
            dutyScheduleInfoMoneyExcelVO.setDUsernameDelete(i.getDUsername());
            return dutyScheduleInfoMoneyExcelVO;
        }).collect(Collectors.toList());
        String tempFilName = UuidUtils.generateUuid() + ".xlsx";
        String fileName = systemConfig.getFileUrl() + File.separator + tempFilName;
        ExcelUtil.exportMoneys(wxpParamDictionaryExcelVOS, fileName);
        XSSFWorkbook xssfWorkbook = null;
        try (InputStream inputStream = new FileInputStream(fileName)) {
            xssfWorkbook = new XSSFWorkbook(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取需要删除的Sheet
        Sheet sheet = xssfWorkbook.getSheetAt(0);
        //删除第9列
        WorkBookUtil.deleteColumn(sheet, 9);
        try (OutputStream fileOut = new FileOutputStream(fileName)) {
            xssfWorkbook.write(fileOut);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tempFilName;
    }

    @Override
    public BaseResult getThisMonthSchedule(Integer year, Integer month) {
        List<LocalDate> betweenTimes = DateUtil.getDatesForThisMONTH(year, month);
        BaseDeptInfo father = baseDeptInfoRepository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getDeptName, systemConfig.getZsCustomName()));
        List<BaseDeptInfo> deptInfoList = guavacacheUtils.getDepts();
        Map<String, BaseDeptInfo> deptInfoMap = deptInfoList.stream().collect(Collectors.toMap(BaseDeptInfo::getId, i -> i));

        DutyScheduleSetCustom dutyScheduleSetCustom = dutyScheduleSetCustomRepository.getOne(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                .le(DutyScheduleSetCustom::getSYearStart, betweenTimes.get(0).getYear())
                .ge(DutyScheduleSetCustom::getSYearEnd, betweenTimes.get(0).getYear())
                .le(DutyScheduleSetCustom::getSMonthStart, betweenTimes.get(0).getMonthValue())
                .ge(DutyScheduleSetCustom::getSMonthEnd, betweenTimes.get(0).getMonthValue())
                .eq(DutyScheduleSetCustom::getCustomId, father.getId())
                .eq(DutyScheduleSetCustom::getSStatus, SStatusEnum.TYPE_SUBMIT.getValue()));
        if (dutyScheduleSetCustom == null) {
            return BaseResult.ok(new ArrayList<>());
        }

        LambdaQueryWrapper<DutyScheduleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DutyScheduleInfo::getSetCustomId, dutyScheduleSetCustom.getId());
        lambdaQueryWrapper.ge(DutyScheduleInfo::getDDay, betweenTimes.get(0));
        lambdaQueryWrapper.le(DutyScheduleInfo::getDDay, betweenTimes.get(1));
        lambdaQueryWrapper.orderByAsc(DutyScheduleInfo::getSType, DutyScheduleInfo::getDDay, DutyScheduleInfo::getDDayString);
        List<DutyScheduleInfo> thisMonthDate = dutyScheduleInfoRepository.list(lambdaQueryWrapper);

        HDMonthScheduleInfoVO hdMonthScheduleInfoVO = new HDMonthScheduleInfoVO();
        HDMonthScheduleInfoDayVO managerInfo = new HDMonthScheduleInfoDayVO();
        HDMonthScheduleInfoDayVO CJInfo = new HDMonthScheduleInfoDayVO();
        ParamLeader GLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                .eq(ParamLeader::getDeptId, father.getId())
                .eq(ParamLeader::getLeaderName, "1"));
        ParamLeader CLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                .eq(ParamLeader::getDeptId, father.getId())
                .eq(ParamLeader::getLeaderName, "2"));
        if (GLeader != null) {
            List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, GLeader.getLeaderCode()));
            if (!CollectionUtils.isEmpty(basePersonInfos)) {
                BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(basePersonInfo.getDeptId());
                managerInfo.setDeptName(baseDeptInfo.getDeptName());
                managerInfo.setPersonName(basePersonInfo.getUsername());
            }
            hdMonthScheduleInfoVO.setGJLeader(managerInfo);
        }
        if (CLeader != null) {
            List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, CLeader.getLeaderCode()));
            if (!CollectionUtils.isEmpty(basePersonInfos)) {
                BasePersonInfo tempBasePerson = basePersonInfos.stream().filter(i -> "0".equals(i.getSideLine()))
                        .findAny().orElse(null);
                if (tempBasePerson == null) {
                    tempBasePerson = basePersonInfos.get(0);
                }
                BasePersonInfo basePersonInfo = tempBasePerson;
                BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(basePersonInfo.getDeptId());
                CJInfo.setDeptName(baseDeptInfo.getDeptName());
                CJInfo.setPersonName(basePersonInfo.getUsername());
            }
            hdMonthScheduleInfoVO.setCJLeader(CJInfo);
        }
        if (CollectionUtils.isEmpty(thisMonthDate)) {
            return BaseResult.ok(hdMonthScheduleInfoVO);
        } else {
            getParentDeptFor(thisMonthDate, deptInfoMap);
            List<HDMonthScheduleInfoDayVO> nights = thisMonthDate.stream()
                    .filter(i ->
                            Arrays.asList("科员", "科领导").contains(i.getDUserjob())
                                    && (i.getDutyTimesString() != null && i.getDutyTimesString().contains("夜间") && !STypeEnum.TYPE_ZMB.getValue().equals(i.getSType()) && !STypeEnum.TYPE_ZYB.getValue().equals(i.getSType())))
                    .sorted(Comparator.comparing(DutyScheduleInfo::getDDay).thenComparing(d -> {
                        if (d.getDutyTimesString().contains("上午")) {
                            return 1;
                        } else if (d.getDutyTimesString().contains("下午")) {
                            return 2;
                        } else if (d.getDutyTimesString().contains("白天")) {
                            return 3;
                        }
                        if (d.getDutyTimesString().contains("夜间")) {
                            return 4;
                        }
                        return 5;
                    })).map(i -> {
                        HDMonthScheduleInfoDayVO hdMonthScheduleInfoDayVO = new HDMonthScheduleInfoDayVO();
                        hdMonthScheduleInfoDayVO.setDay(i.getDDayString() != null ? i.getDDayString().replace("日星", "日(星") + ")" : "");
                        hdMonthScheduleInfoDayVO.setDeptName(i.getDDeptname());
                        hdMonthScheduleInfoDayVO.setPersonName(i.getDUsername());
                        hdMonthScheduleInfoDayVO.setPersonNo(i.getDUserno());
                        hdMonthScheduleInfoDayVO.setShortNo(i.getPhoneShort());
                        hdMonthScheduleInfoDayVO.setTime("夜间");
                        if (STypeEnum.TYPE_ZMB.getValue().equals(i.getSType())) {
                            hdMonthScheduleInfoDayVO.setGJLeader(managerInfo);
                            hdMonthScheduleInfoDayVO.setCJLeader(CJInfo);
                        } else {
                            hdMonthScheduleInfoDayVO.setGJLeader(getGJForI(i, thisMonthDate));
                            hdMonthScheduleInfoDayVO.setCJLeader(getCJForI(i, thisMonthDate));
                        }
                        return hdMonthScheduleInfoDayVO;
                    }).collect(Collectors.toList());
            List<HDMonthScheduleInfoDayVO> weekends = thisMonthDate.stream().filter(i ->
                            Arrays.asList("科员", "科领导").contains(i.getDUserjob())
                                    && !(i.getDutyTimesString() != null && i.getDutyTimesString().contains("夜间") && !STypeEnum.TYPE_ZMB.getValue().equals(i.getSType()) && !STypeEnum.TYPE_ZYB.getValue().equals(i.getSType())))
                    .sorted(Comparator.comparing(DutyScheduleInfo::getDDay).thenComparing(d -> {
                        if (d.getDutyTimesString().contains("上午")) {
                            return 1;
                        } else if (d.getDutyTimesString().contains("下午")) {
                            return 2;
                        } else if (d.getDutyTimesString().contains("白天")) {
                            return 3;
                        }
                        if (d.getDutyTimesString().contains("夜间")) {
                            return 4;
                        }
                        return 5;
                    })).map(i -> {
                        HDMonthScheduleInfoDayVO hdMonthScheduleInfoDayVO = new HDMonthScheduleInfoDayVO();
                        hdMonthScheduleInfoDayVO.setDay(i.getDDayString() != null ? i.getDDayString().replace("日星", "日(星") + ")" : "");
                        hdMonthScheduleInfoDayVO.setDeptName(i.getDDeptname());
                        hdMonthScheduleInfoDayVO.setPersonName(i.getDUsername());
                        hdMonthScheduleInfoDayVO.setPersonNo(i.getDUserno());
                        hdMonthScheduleInfoDayVO.setShortNo(i.getPhoneShort());
                        ParamDuty paramDuty = guavacacheUtils.getParamDuty(i.getDutyTimesId());
                        hdMonthScheduleInfoDayVO.setTime(DTypeEnum.TYPE_DAY_TIME.getValueByCode(paramDuty.getDType()));
                        if (!STypeEnum.TYPE_ZMB.getValue().equals(i.getSType())) {
                            hdMonthScheduleInfoDayVO.setGJLeader(managerInfo);
                            hdMonthScheduleInfoDayVO.setCJLeader(CJInfo);
                        } else {
                            hdMonthScheduleInfoDayVO.setGJLeader(getGJForI(i, thisMonthDate));
                            hdMonthScheduleInfoDayVO.setCJLeader(getCJForI(i, thisMonthDate));
                        }
                        return hdMonthScheduleInfoDayVO;
                    }).collect(Collectors.toList());
            hdMonthScheduleInfoVO.setNights(nights);
            hdMonthScheduleInfoVO.setWeekends(weekends);
            return BaseResult.ok(hdMonthScheduleInfoVO);
        }
    }

    private HDMonthScheduleInfoDayVO getCJForI(DutyScheduleInfo i, List<DutyScheduleInfo> thisMonthDate) {
        DutyScheduleInfo temp = thisMonthDate.stream().filter(j -> "处领导".equals(j.getDUserjob()) && i.getDutyTimesId().equals(j.getDutyTimesId()) &&
                i.getDDay().equals(j.getDDay())).findFirst().orElse(null);
        if (temp == null) {
            return null;
        } else {
            HDMonthScheduleInfoDayVO hdMonthScheduleInfoDayVO = new HDMonthScheduleInfoDayVO();
            hdMonthScheduleInfoDayVO.setDay(temp.getDDayString() != null ? i.getDDayString().replace("日星", "日(星") + ")" : "");
            hdMonthScheduleInfoDayVO.setDeptName(temp.getDDeptname());
            hdMonthScheduleInfoDayVO.setPersonName(temp.getDUsername());
            hdMonthScheduleInfoDayVO.setPersonNo(temp.getDUserno());
            hdMonthScheduleInfoDayVO.setShortNo(temp.getPhoneShort());
            return hdMonthScheduleInfoDayVO;
        }

    }

    private HDMonthScheduleInfoDayVO getGJForI(DutyScheduleInfo i, List<DutyScheduleInfo> thisMonthDate) {
        DutyScheduleInfo temp = thisMonthDate.stream().filter(j -> "关领导".equals(j.getDUserjob()) && i.getDutyTimesId().equals(j.getDutyTimesId()) &&
                i.getDDay().equals(j.getDDay())).findFirst().orElse(null);
        if (temp == null) {
            return null;
        } else {
            HDMonthScheduleInfoDayVO hdMonthScheduleInfoDayVO = new HDMonthScheduleInfoDayVO();
            hdMonthScheduleInfoDayVO.setDay(temp.getDDayString() != null ? i.getDDayString().replace("日星", "日(星") + ")" : "");
            hdMonthScheduleInfoDayVO.setDeptName(temp.getDDeptname());
            hdMonthScheduleInfoDayVO.setPersonName(temp.getDUsername());
            hdMonthScheduleInfoDayVO.setPersonNo(temp.getDUserno());
            hdMonthScheduleInfoDayVO.setShortNo(temp.getPhoneShort());
            return hdMonthScheduleInfoDayVO;
        }
    }

    @Override
    public BaseResult getTodaySchedule() {
        BaseDeptInfo father = baseDeptInfoRepository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
                .eq(BaseDeptInfo::getDeptName, systemConfig.getZsCustomName()));
        List<LocalDate> betweenTimes = DateUtil.getDatesForToday();
        List<DutyScheduleSetCustom> dutyScheduleSetCustom = dutyScheduleSetCustomRepository.list(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                .le(DutyScheduleSetCustom::getSYearStart, betweenTimes.get(1).getYear())
                .ge(DutyScheduleSetCustom::getSYearEnd, betweenTimes.get(0).getYear())
                .le(DutyScheduleSetCustom::getSMonthStart, betweenTimes.get(1).getMonthValue())
                .ge(DutyScheduleSetCustom::getSMonthEnd, betweenTimes.get(0).getMonthValue())
                .eq(DutyScheduleSetCustom::getCustomId, father.getId())
                .eq(DutyScheduleSetCustom::getSStatus, SStatusEnum.TYPE_SUBMIT.getValue()));
        if (dutyScheduleSetCustom == null) {
            return BaseResult.ok(new ArrayList<>());
        }
        LambdaQueryWrapper<DutyScheduleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DutyScheduleInfo::getSetCustomId, dutyScheduleSetCustom.stream().map(DutyScheduleSetCustom::getId).collect(Collectors.toList()));
        lambdaQueryWrapper.ge(DutyScheduleInfo::getDDay, betweenTimes.get(0));
        lambdaQueryWrapper.le(DutyScheduleInfo::getDDay, betweenTimes.get(1));
        lambdaQueryWrapper.in(DutyScheduleInfo::getDUserjob, Arrays.asList("科员", "科领导"));
//        if (!StringUtils.isEmpty(dutyScheduleInfo.getSType())) {
//            lambdaQueryWrapper.eq(DutyScheduleInfo::getSType, dutyScheduleInfo.getSType());
//        }
        lambdaQueryWrapper.orderByAsc(DutyScheduleInfo::getSType, DutyScheduleInfo::getDDay, DutyScheduleInfo::getDDayString);
        List<DutyScheduleInfo> thisMonthDate = dutyScheduleInfoRepository.list(lambdaQueryWrapper);
        List<HDMonthScheduleInfoDayVO> weekends = thisMonthDate.stream()
                .sorted(Comparator.comparing(DutyScheduleInfo::getDDay).thenComparing(d -> {
                    if (d.getDutyTimesString().contains("上午")) {
                        return 1;
                    } else if (d.getDutyTimesString().contains("下午")) {
                        return 2;
                    } else if (d.getDutyTimesString().contains("白天")) {
                        return 3;
                    }
                    if (d.getDutyTimesString().contains("夜间")) {
                        return 4;
                    }
                    return 5;
                })).map(i -> {
                    HDMonthScheduleInfoDayVO hdMonthScheduleInfoDayVO = new HDMonthScheduleInfoDayVO();
                    hdMonthScheduleInfoDayVO.setDay(i.getDDayString() != null ? i.getDDayString().replace("日星", "日(星") + ")" : "");
                    hdMonthScheduleInfoDayVO.setDeptName(i.getDDeptname());
                    hdMonthScheduleInfoDayVO.setPersonName(i.getDUsername());
                    hdMonthScheduleInfoDayVO.setPersonNo(i.getDUserno());
                    hdMonthScheduleInfoDayVO.setShortNo(i.getPhoneShort());
                    ParamDuty paramDuty = guavacacheUtils.getParamDuty(i.getDutyTimesId());
                    hdMonthScheduleInfoDayVO.setTime(DTypeEnum.TYPE_DAY_TIME.getValueByCode(paramDuty.getDType()));
                    return hdMonthScheduleInfoDayVO;
                }).collect(Collectors.toList());
        return BaseResult.ok(weekends);
    }

    @Override
    public BaseResult<DutyScheduleInfoTimeDTO> nowUser(String customnName, List<BaseDeptInfo> baseDeptInfos, List<DutyScheduleInfo> dutyScheduleInfos) {
        return null;
    }

    @Override
    public BaseResult<DutyScheduleInfoTimeDTO> nowUser(String customnName) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime tomorrow = LocalDateTime.now().toLocalDate().plusDays(1l).atStartOfDay();
        DutyScheduleInfoTimeDTO todayDTO = getTimeDTOForNow(customnName, now);
        DutyScheduleInfoTimeDTO tomorrowDTO = getTimeDTOForNow(customnName, tomorrow);
        String todayString = getStringByTimeDTO(todayDTO);
        String tomorrowString = getStringByTimeDTO(tomorrowDTO);
        todayDTO.setTomorrowPerson(tomorrowString);
        todayDTO.setTodayPerson(todayString);
        return BaseResult.ok(todayDTO);
    }

//    @Override
//    public BaseResult getNowSchedule() {
//        BaseDeptInfo father=baseDeptInfoRepository.getOne(new LambdaQueryWrapper<BaseDeptInfo>()
//                .eq(BaseDeptInfo::getDeptName,"海关总署"));
//        List<LocalDate> betweenTimes=DateUtil.getDatesForToday();
//        List<DutyScheduleSetCustom> dutyScheduleSetCustom = dutyScheduleSetCustomRepository.list(new LambdaQueryWrapper<DutyScheduleSetCustom>()
//                .le(DutyScheduleSetCustom::getSYearStart, betweenTimes.get(1).getYear())
//                .ge(DutyScheduleSetCustom::getSYearEnd, betweenTimes.get(0).getYear())
//                .le(DutyScheduleSetCustom::getSMonthStart, betweenTimes.get(1).getMonthValue())
//                .ge(DutyScheduleSetCustom::getSMonthEnd, betweenTimes.get(0).getMonthValue())
//                .eq(DutyScheduleSetCustom::getCustomId, father.getId())
//                .eq(DutyScheduleSetCustom::getSStatus, SStatusEnum.TYPE_SUBMIT.getValue()));
//        if (dutyScheduleSetCustom == null) {
//            return BaseResult.ok(new ArrayList<>());
//        }
//        LambdaQueryWrapper<DutyScheduleInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.in(DutyScheduleInfo::getSetCustomId, dutyScheduleSetCustom.stream().map(DutyScheduleSetCustom::getId).collect(Collectors.toList()));
//        lambdaQueryWrapper.ge(DutyScheduleInfo::getDDay, betweenTimes.get(0));
//        lambdaQueryWrapper.le(DutyScheduleInfo::getDDay,betweenTimes.get(1));
//        lambdaQueryWrapper.in(DutyScheduleInfo::getDUserjob,Arrays.asList("科员","关领导"));

    /// /        if (!StringUtils.isEmpty(dutyScheduleInfo.getSType())) {
    /// /            lambdaQueryWrapper.eq(DutyScheduleInfo::getSType, dutyScheduleInfo.getSType());
    /// /        }
//        lambdaQueryWrapper.orderByAsc(DutyScheduleInfo::getSType,DutyScheduleInfo::getDDay,DutyScheduleInfo::getDDayString);
//        List<DutyScheduleInfo> thisMonthDate= dutyScheduleInfoRepository.list(lambdaQueryWrapper);
//        List<HDMonthScheduleInfoDayVO> weekends=thisMonthDate.stream()
//                .sorted(Comparator.comparing(DutyScheduleInfo::getDDay).thenComparing(d->{
//                    if (d.getDutyTimesString().contains("上午")){
//                        return 1;
//                    }else if (d.getDutyTimesString().contains("下午")) {
//                        return 2;
//                    }else if (d.getDutyTimesString().contains("白天")) {
//                        return 3;
//                    }if (d.getDutyTimesString().contains("夜间")) {
//                        return 4;
//                    }
//                    return 5;
//                })).map(i->{
//                    HDMonthScheduleInfoDayVO hdMonthScheduleInfoDayVO=new HDMonthScheduleInfoDayVO();
//                    hdMonthScheduleInfoDayVO.setDay(i.getDDayString()!=null?i.getDDayString().replace("日星","日(星")+")":"");
//                    hdMonthScheduleInfoDayVO.setDeptName(i.getDDeptname());
//                    hdMonthScheduleInfoDayVO.setPersonName(i.getDUsername());
//                    hdMonthScheduleInfoDayVO.setPersonNo(i.getDUserno());
//                    hdMonthScheduleInfoDayVO.setShortNo(i.getPhoneShort());
//                    ParamDuty paramDuty=guavacacheUtils.getParamDuty(i.getDutyTimesId());
//                    hdMonthScheduleInfoDayVO.setTime(DTypeEnum.TYPE_DAY_TIME.getValueByCode(paramDuty.getDType()));
//                    return hdMonthScheduleInfoDayVO;
//                }).collect(Collectors.toList());
//        return BaseResult.ok(weekends);
//    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object saveInfo(DutyScheduleInfoSaveVO dutyScheduleInfoSaveVO, UserInfoDetailVO userInfoDetailVO) throws Exception {
        if (!userInfoDetailVO.getRole().contains("ZGGLY")) {
            return doSaveInfo(dutyScheduleInfoSaveVO, userInfoDetailVO);
        } else {
            return doSaveInfoZG(dutyScheduleInfoSaveVO, userInfoDetailVO);
        }
    }

    private Object doSaveInfoZG(DutyScheduleInfoSaveVO dutyScheduleInfoSaveVO, UserInfoDetailVO userInfoDetailVO) throws Exception {
        DutyScheduleInfo dutyScheduleInfo = new DutyScheduleInfo();
        BeanUtils.copyProperties(dutyScheduleInfoSaveVO, dutyScheduleInfo);
//        if (StringUtils.isEmpty(dutyScheduleInfoSaveVO.getSType())){
//            throw new Exception("sType不能为空");
//        }else {
        if (dutyScheduleInfoSaveVO.getDUserno() == null) {
            throw new Exception("工号不能为空！");
        } else {
            List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, dutyScheduleInfoSaveVO.getDUserno()));
            if (CollectionUtils.isEmpty(basePersonInfos)) {
                throw new Exception("无该工号对应人员!");
            }
            basePersonInfos = basePersonInfos.stream().filter(i -> i.getDeptId() != null && baseDeptInfoRepository.getById(i.getDeptId()) != null).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(basePersonInfos)) {
                throw new Exception("无该工号对应人员部门!");
            }
            BasePersonInfo tempBasePerson = basePersonInfos.stream().filter(i -> "0".equals(i.getSideLine()))
                    .findAny().orElse(null);
            if (tempBasePerson == null) {
                tempBasePerson = basePersonInfos.get(0);
            }
            BasePersonInfo basePersonInfo = tempBasePerson;
            BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(basePersonInfo.getDeptId());
            if (dutyScheduleInfo.getDDeptname() == null) {
                dutyScheduleInfo.setDDeptname(baseDeptInfo.getDeptName());
            }
            if (dutyScheduleInfo.getDutyType() != null) {
                dutyScheduleInfo.setDUserjob(getDuserJob(dutyScheduleInfo.getDutyType()));
            }
            if (dutyScheduleInfo.getDDept() == null) {
                dutyScheduleInfo.setDDept(baseDeptInfo.getId());
            }
            if (dutyScheduleInfo.getDPhone() == null) {
                dutyScheduleInfo.setDPhone(basePersonInfo.getPhone());
            }
            if (dutyScheduleInfo.getDUsername() == null) {
                dutyScheduleInfo.setDUsername(basePersonInfo.getUsername());
            }
            dutyScheduleInfo.setDUserno(basePersonInfo.getUserno());
            if (dutyScheduleInfo.getRankCode() == null) {
                dutyScheduleInfo.setRankCode(basePersonInfo.getRankCode());

            }
            if (dutyScheduleInfo.getDutypost() == null) {
                dutyScheduleInfo.setDutypost(basePersonInfo.getRankCode() != null ? getDupostByH4a(basePersonInfo.getRealRackCode()) : "");
            }
            if (dutyScheduleInfo.getPhoneShort() == null) {
                dutyScheduleInfo.setPhoneShort(basePersonInfo.getPhoneShort());
            }
            if (StringUtils.isEmpty(dutyScheduleInfo.getDPhoneLand())) {
                dutyScheduleInfo.setDPhoneLand(basePersonInfo.getPhoneLand());

            }
        }

        LocalDateTime startTime = LocalDateTime.of(dutyScheduleInfoSaveVO.getDDay(), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dutyScheduleInfoSaveVO.getDDay(), LocalTime.MAX);
        LambdaQueryWrapper<DutyScheduleInfo> checkQuery = new LambdaQueryWrapper<DutyScheduleInfo>()
                .eq(DutyScheduleInfo::getDutyType, dutyScheduleInfoSaveVO.getDutyType())
                .eq(DutyScheduleInfo::getCustomId, userInfoDetailVO.getCustomscode())
                .eq(DutyScheduleInfo::getDutyTimesId, dutyScheduleInfoSaveVO.getDutyTimesId())
                .between(DutyScheduleInfo::getDDay, startTime, endTime);
        if (dutyScheduleInfoSaveVO.getId() != null) {
            checkQuery.ne(DutyScheduleInfo::getId, dutyScheduleInfoSaveVO.getId());
        }
        List<DutyScheduleInfo> scheduleInfoTimesId = dutyScheduleInfoRepository.list(checkQuery);
        if (scheduleInfoTimesId.size() > 0) {
            if (scheduleInfoTimesId.get(0).getDutyType().equals(dutyScheduleInfoSaveVO.getDutyType())) {
                throw new Exception("同一天内不能有相同的值班类型");
            }
        }
        String dayOfWeek = DateUtil.getDaysOfWeek((long) dutyScheduleInfo.getDDay().getYear(), (long) dutyScheduleInfo.getDDay().getMonth().getValue(), dutyScheduleInfo.getDDay().getDayOfMonth());
        dutyScheduleInfo.setDDayString(dutyScheduleInfo.getDDay().getMonth().getValue() + "月" + dutyScheduleInfo.getDDay().getDayOfMonth() + "日" + dayOfWeek);
        if (StringUtils.isEmpty(dutyScheduleInfo.getId())) {
            dutyScheduleInfo.setCreateBy(userInfoDetailVO.getUserId());
            dutyScheduleInfo.setCreateTime(LocalDateTime.now());
            dutyScheduleInfo.setUpdateBy(userInfoDetailVO.getUserId());
            dutyScheduleInfo.setDOperatorName(userInfoDetailVO.getUserName());
            dutyScheduleInfo.setUpdateTime(LocalDateTime.now());
            dutyScheduleInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            dutyScheduleInfo.setCustomId(userInfoDetailVO.getCustomscode());
            dutyScheduleInfo.setCustomName(userInfoDetailVO.getCustomsName());
            dutyScheduleInfoRepository.save(dutyScheduleInfo);
        } else {
            DutyScheduleInfo byId = dutyScheduleInfoRepository.getById(dutyScheduleInfo.getId());
            dutyScheduleInfo.setDOperatorName(userInfoDetailVO.getUserName());
            dutyScheduleInfo.setUpdateBy(userInfoDetailVO.getUserId());
            dutyScheduleInfo.setUpdateTime(LocalDateTime.now());
            dutyScheduleInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            if (byId != null) {
                dutyScheduleInfo.setRecVersion(byId.getRecVersion());
            }
            dutyScheduleInfoRepository.updateById(dutyScheduleInfo);
            dutySignInfoRepository.remove(new LambdaQueryWrapper<DutySignInfo>()
                    .eq(DutySignInfo::getDId, dutyScheduleInfo.getId()));
        }
        DutySignInfo dutySignInfo = new DutySignInfo();
        if (!StringUtils.isEmpty(dutyScheduleInfoSaveVO.getDUserno())) {
            dutySignInfo.setDId(dutyScheduleInfo.getId());
            dutySignInfo.setCreateBy(userInfoDetailVO.getUserId());
            dutySignInfo.setCreateTime(LocalDateTime.now());
            dutySignInfo.setUpdateBy(userInfoDetailVO.getUserId());
            dutySignInfo.setUpdateTime(LocalDateTime.now());
            dutySignInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            dutySignInfoRepository.save(dutySignInfo);
        }
        return true;
    }

    private String getDuserJob(String dutyType) {
        String result = "";
        if (dutyType == null) {
            return result;
        }
        switch (dutyType) {
            case "1":
                result = "关领导";
                break;
            case "2":
                result = "处领导";
                break;
            case "3":
                result = "科领导";
                break;
            case "4":
                result = "署领导";
                break;
            case "5":
                result = "司局领导";
                break;
            case "6":
                result = "处领导";
                break;
            case "7":
                result = "主值班员";
                break;
            case "8":
                result = "副值班员";
                break;
            default:
                return "其他";
        }
        return result;
    }

    private Object doSaveInfo(DutyScheduleInfoSaveVO dutyScheduleInfoSaveVO, UserInfoDetailVO userInfoDetailVO) throws Exception {
        DutyScheduleInfo dutyScheduleInfo = new DutyScheduleInfo();
        BeanUtils.copyProperties(dutyScheduleInfoSaveVO, dutyScheduleInfo);
        if (!CollectionUtils.isEmpty(dutyScheduleInfoSaveVO.getDDept())) {
            dutyScheduleInfo.setDDept(dutyScheduleInfoSaveVO.getDDept().get(dutyScheduleInfoSaveVO
                    .getDDept().size() - 1));
            BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(dutyScheduleInfo.getDDept());
            if (baseDeptInfo != null) {
                dutyScheduleInfo.setDDeptname(baseDeptInfo.getDeptName());
            }
        }
//        if (StringUtils.isEmpty(dutyScheduleInfoSaveVO.getSType())){
//            throw new Exception("sType不能为空");
//        }else {
        if (dutyScheduleInfoSaveVO.getDDay() == null) {
            throw new Exception("值班日期不能为空");
        } else {
            DutyScheduleSetCustom dutyScheduleSetCustom = dutyScheduleSetCustomRepository.getOne(new LambdaQueryWrapper<DutyScheduleSetCustom>()
                    .and(wrapper ->
                            wrapper.le(DutyScheduleSetCustom::getStartDate, LocalDate.of(dutyScheduleInfoSaveVO.getDDay().getYear(), dutyScheduleInfoSaveVO.getDDay().getMonth().getValue(), 1))
                                    .ge(DutyScheduleSetCustom::getEndDate, LocalDate.of(dutyScheduleInfoSaveVO.getDDay().getYear(), dutyScheduleInfoSaveVO.getDDay().getMonth().getValue(), 1).plusMonths(1).minusDays(1).minusMonths(1))
                    )
                    .eq(DutyScheduleSetCustom::getCustomId, userInfoDetailVO.getCustomscode()
                    ));
            if (dutyScheduleSetCustom == null) {
                throw new Exception("该时段没有进行过总体排班");
            }
            dutyScheduleInfo.setSetCustomId(dutyScheduleSetCustom.getId());
            BaseDeptInfo custom = baseDeptInfoRepository.getById(dutyScheduleSetCustom.getCustomId());
            if (custom != null) {
                dutyScheduleInfo.setCustomId(custom.getId());
                dutyScheduleInfo.setCustomName(custom.getDeptName());
            }
        }
        if (dutyScheduleInfoSaveVO.getDutyTimesId() == null) {
            throw new Exception("值班时段不能为空");
        } else {
            ParamDuty paramDuty = guavacacheUtils.getParamDuty(dutyScheduleInfoSaveVO.getDutyTimesId());
            if (paramDuty != null) {
                dutyScheduleInfo.setDutyTimesString(DTypeEnum.TYPE_DAY_TIME.getValueByCode(paramDuty.getDType()) + "(" + paramDuty.getDStartTime().getHour() + ":"
                        + paramDuty.getDStartTime().getMinute() + "~" + paramDuty.getDEndTime().getHour() + ":"
                        + paramDuty.getDEndTime().getMinute() + ")");
            }
            dutyScheduleInfo.setDutyParamType(paramDuty.getDType());
            if (paramDuty.getDStartTime().compareTo(paramDuty.getDEndTime()) < 0) {
                dutyScheduleInfo.setDStartDateTime(dutyScheduleInfo.getDDay().atTime(paramDuty.getDStartTime()));
                dutyScheduleInfo.setDEndDateTime(dutyScheduleInfo.getDDay().atTime(paramDuty.getDEndTime()));
            } else {
                dutyScheduleInfo.setDStartDateTime(dutyScheduleInfo.getDDay().atTime(paramDuty.getDStartTime()));
                dutyScheduleInfo.setDEndDateTime(dutyScheduleInfo.getDDay().plusDays(1l).atTime(paramDuty.getDEndTime()));
            }
//            dutyScheduleInfo.setDType("1");
        }
        if (dutyScheduleInfoSaveVO.getDUserno() == null) {
            throw new Exception("工号不能为空！");
        } else {
            List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, dutyScheduleInfoSaveVO.getDUserno()));
            if (CollectionUtils.isEmpty(basePersonInfos)) {
                throw new Exception("无该工号对应人员!");
            }
            basePersonInfos = basePersonInfos.stream().filter(i -> i.getDeptId() != null && baseDeptInfoRepository.getById(i.getDeptId()) != null).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(basePersonInfos)) {
                throw new Exception("无该工号对应人员部门!");
            }
            BasePersonInfo tempBasePerson = basePersonInfos.stream().filter(i -> "0".equals(i.getSideLine()))
                    .findAny().orElse(null);
            if (tempBasePerson == null) {
                tempBasePerson = basePersonInfos.get(0);
            }
            BasePersonInfo basePersonInfo = tempBasePerson;
            BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(basePersonInfo.getDeptId());
//            if (StringUtils.isEmpty(dutyScheduleInfo.getDDeptname())) {
            dutyScheduleInfo.setDDeptname(baseDeptInfo.getDeptName());
//            }
//            if (StringUtils.isEmpty(dutyScheduleInfo.getDDept())) {
            dutyScheduleInfo.setDDept(baseDeptInfo.getId());
//            }
//            if (StringUtils.isEmpty(dutyScheduleInfo.getDPhone())) {
//                dutyScheduleInfo.setDPhone(basePersonInfo.getPhone());
//                dutyScheduleInfo.setDPhone(basePersonInfo.getPhone());
            dutyScheduleInfo.setDPhone(dutyScheduleInfoSaveVO.getDPhone());
//            }
//            if (StringUtils.isEmpty(dutyScheduleInfo.getDPhoneLand())) {
//                dutyScheduleInfo.setDPhoneLand(basePersonInfo.getPhoneLand());
            dutyScheduleInfo.setDPhoneLand(dutyScheduleInfoSaveVO.getDPhoneLand());
//            }
//            if (StringUtils.isEmpty(dutyScheduleInfo.getDUserno())) {
            dutyScheduleInfo.setDUserno(basePersonInfo.getUserno());
//            }
//            if (StringUtils.isEmpty(dutyScheduleInfo.getRankCode())) {
            dutyScheduleInfo.setRankCode(basePersonInfo.getRankCode());
//            }
//            if (StringUtils.isEmpty(dutyScheduleInfo.getDutypost())) {
            dutyScheduleInfo.setDutypost(basePersonInfo.getRankCode() != null ? getDupostByH4a(basePersonInfo.getRealRackCode()) : "");
//            }
//            if (StringUtils.isEmpty(dutyScheduleInfo.getPhoneShort())) {
//                dutyScheduleInfo.setPhoneShort(basePersonInfo.getPhoneShort());
            dutyScheduleInfo.setPhoneShort(dutyScheduleInfoSaveVO.getPhoneShort());
//            }
//            if (StringUtils.isEmpty(dutyScheduleInfo.getDPhoneLand())) {
//                dutyScheduleInfo.setDPhoneLand(basePersonInfo.getPhoneLand());
//            }
        }
        LocalDateTime startTime = LocalDateTime.of(dutyScheduleInfoSaveVO.getDDay(), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(dutyScheduleInfoSaveVO.getDDay(), LocalTime.MAX);
        LambdaQueryWrapper<DutyScheduleInfo> checkQuery = new LambdaQueryWrapper<DutyScheduleInfo>()
                .eq(DutyScheduleInfo::getDutyType, dutyScheduleInfoSaveVO.getDutyType())
                .eq(DutyScheduleInfo::getSType, dutyScheduleInfoSaveVO.getSType())
                .eq(DutyScheduleInfo::getDutyTimesId, dutyScheduleInfoSaveVO.getDutyTimesId())
                .eq(DutyScheduleInfo::getCustomId, userInfoDetailVO.getCustomscode())
                .between(DutyScheduleInfo::getDDay, startTime, endTime);
        if (dutyScheduleInfoSaveVO.getId() != null) {
            checkQuery.ne(DutyScheduleInfo::getId, dutyScheduleInfoSaveVO.getId());
        }
        List<DutyScheduleInfo> scheduleInfoTimesId = dutyScheduleInfoRepository.list(checkQuery);
        if (dutyScheduleInfoSaveVO.getId() == null && scheduleInfoTimesId.size() > 0) {
//            log.info("startTime:"+startTime.toString());
//            log.info("endTime:"+endTime.toString());
//            log.info("===========scheduleInfoTimesId的stype："+scheduleInfoTimesId.get(0).getSType());
//            log.info("===========dutyScheduleInfoSaveVO的stype："+dutyScheduleInfoSaveVO.getSType());
//            log.info("scheduleInfoTimesId:"+scheduleInfoTimesId.get(0).toString());
//            log.info("dutyScheduleInfoSaveVO:"+dutyScheduleInfoSaveVO.toString());
//            if (!scheduleInfoTimesId.get(0).getSType().equals(dutyScheduleInfoSaveVO.getSType())){
            throw new Exception("同一天内只能有一种排班类型");
//            }
        }

        switch (dutyScheduleInfo.getDType()) {
            case "1":
                dutyScheduleInfoSaveVO.setDutyType(DutyTypeEnum.DIRECTLY_SECTION_MEMBER.getValue());
                break;
            case "2":
                dutyScheduleInfoSaveVO.setDutyType(DutyTypeEnum.DIRECTLY_DIVISION_LEADER.getValue());
        }
        String dayOfWeek = DateUtil.getDaysOfWeek((long) dutyScheduleInfo.getDDay().getYear(), (long) dutyScheduleInfo.getDDay().getMonth().getValue(), dutyScheduleInfo.getDDay().getDayOfMonth());
        dutyScheduleInfo.setDDayString(dutyScheduleInfo.getDDay().getMonth().getValue() + "月" + dutyScheduleInfo.getDDay().getDayOfMonth() + "日" + dayOfWeek);
//        DutyScheduleInfo scheduleInfo = dutyScheduleInfoRepository.getOne(new LambdaQueryWrapper<DutyScheduleInfo>()
//                .eq(DutyScheduleInfo::getSType, dutyScheduleInfoSaveVO.getSType())
//                .eq(DutyScheduleInfo::getDutyTimesId, dutyScheduleInfoSaveVO.getDutyTimesId())
//                .between(DutyScheduleInfo::getDDay, startTime,endTime)
//                .eq(DutyScheduleInfo::getDutyType, dutyScheduleInfoSaveVO.getDutyType()),false);
//        if (scheduleInfo!=null){
//            throw new Exception("该班次已存在值班人员");
//        }
//        if (dutyScheduleInfoSaveVO.getDDayString()==null) {
//            String dayOfWeek = DateUtil.getDaysOfWeek((long) dutyScheduleInfoSaveVO.getDDay().getYear(), (long) dutyScheduleInfoSaveVO.getDDay().getMonth().getValue(), dutyScheduleInfoSaveVO.getDDay().getDayOfMonth());
        ParamDuty paramDuty = guavacacheUtils.getParamDuty(dutyScheduleInfoSaveVO.getDutyTimesId());
        if (paramDuty != null && !StringUtils.isEmpty(paramDuty.getId())) {
            dutyScheduleInfo.setDutyTimesString(DTypeEnum.TYPE_DAY_TIME.getValueByCode(paramDuty.getDType()) + "(" + paramDuty.getDStartTime().getHour() + ":"
                    + paramDuty.getDStartTime().getMinute() + "~" + paramDuty.getDEndTime().getHour() + ":"
                    + paramDuty.getDEndTime().getMinute() + ")");
            dutyScheduleInfo.setDutyParamType(paramDuty.getDType());
        }
//        }
//        updateScheduleRecord(dutyScheduleInfo);
        if (StringUtils.isEmpty(dutyScheduleInfo.getId())) {
            dutyScheduleInfo.setCreateBy(userInfoDetailVO.getUserId());
            dutyScheduleInfo.setCreateTime(LocalDateTime.now());
            dutyScheduleInfo.setUpdateBy(userInfoDetailVO.getUserId());
            dutyScheduleInfo.setDOperatorName(userInfoDetailVO.getUserName());
            dutyScheduleInfo.setUpdateTime(LocalDateTime.now());
            dutyScheduleInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            switch (dutyScheduleInfo.getDType()) {
                case "1":
                    dutyScheduleInfo.setDutyType(DutyTypeEnum.DIRECTLY_SECTION_MEMBER.getValue());
                    break;
                case "2":
                    dutyScheduleInfo.setDutyType(DutyTypeEnum.DIRECTLY_DIVISION_LEADER.getValue());
            }
            dutyScheduleInfoRepository.save(dutyScheduleInfo);
        } else {
            DutyScheduleInfo byId = dutyScheduleInfoRepository.getById(dutyScheduleInfo.getId());
            dutyScheduleInfo.setDOperatorName(userInfoDetailVO.getUserName());
            dutyScheduleInfo.setUpdateBy(userInfoDetailVO.getUserId());
            dutyScheduleInfo.setUpdateTime(LocalDateTime.now());
            dutyScheduleInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            if (byId != null) {
                dutyScheduleInfo.setRecVersion(byId.getRecVersion());
            }
            dutyScheduleInfoRepository.updateById(dutyScheduleInfo);
            dutySignInfoRepository.remove(new LambdaQueryWrapper<DutySignInfo>()
                    .eq(DutySignInfo::getDId, dutyScheduleInfo.getId()));
        }
        DutySignInfo dutySignInfo = new DutySignInfo();
        if (!StringUtils.isEmpty(dutyScheduleInfoSaveVO.getDUserno())) {
            dutySignInfo.setDId(dutyScheduleInfo.getId());
            dutySignInfo.setCreateBy(userInfoDetailVO.getUserId());
            dutySignInfo.setCreateTime(LocalDateTime.now());
            dutySignInfo.setUpdateBy(userInfoDetailVO.getUserId());
            dutySignInfo.setUpdateTime(LocalDateTime.now());
            dutySignInfo.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            dutySignInfoRepository.save(dutySignInfo);
        }
        return true;
    }

    /**
     * "科领导"
     * "关领导"
     * "处领导"
     *
     * @param dutyScheduleInfo
     */
    private void updateScheduleRecord(DutyScheduleInfo dutyScheduleInfo) {
        String recordStype;
        switch (dutyScheduleInfo.getSType()) {
            case "1":
                recordStype = DutyScheduleTypeEnum.TYPE_COMMON.getValue();
                break;
            case "2":
                if ("科领导".equals(dutyScheduleInfo.getDUserjob())) {
                    recordStype = DutyScheduleTypeEnum.TYPE_HOILDAY.getValue();
                } else {
                    recordStype = DutyScheduleTypeEnum.TYPE_HOILDAY_DLEVEL.getValue();
                }
                break;
            case "3":
                if ("科领导".equals(dutyScheduleInfo.getDUserjob())) {
                    recordStype = DutyScheduleTypeEnum.TYPE_IMPORTANT.getValue();
                } else {
                    recordStype = DutyScheduleTypeEnum.TYPE_IMPORTANT_DLEVEL.getValue();
                }
                break;
            default:
                recordStype = DutyScheduleTypeEnum.TYPE_COMMON.getValue();
        }
        DutyScheduleSetCustomRecord dutyScheduleSetCustomRecord = dutyScheduleSetCustomRecordRepository.getOne(
                new LambdaQueryWrapper<DutyScheduleSetCustomRecord>()
                        .eq(DutyScheduleSetCustomRecord::getDeptId, dutyScheduleInfo.getDDept())
                        .eq(DutyScheduleSetCustomRecord::getSType, recordStype)
                , false);
        if (dutyScheduleSetCustomRecord == null) {
            return;
        }
        if (StringUtils.isEmpty(dutyScheduleInfo.getId())) {
            dutyScheduleSetCustomRecord.setTotalCount(dutyScheduleSetCustomRecord.getTotalCount() + 1);
            if (DutyScheduleSetCustomRecordStatusEnum.NOT_PASSED_YET.getValue().equals(dutyScheduleSetCustomRecord.getStatus()) &&
                    dutyScheduleSetCustomRecord.getTotalCount().equals(dutyScheduleSetCustomRecord.getNeedCount())) {
                dutyScheduleSetCustomRecord.setStatus(DutyScheduleSetCustomRecordStatusEnum.IS_PASSED.getValue());
            }
            dutyScheduleSetCustomRecordRepository.updateById(dutyScheduleSetCustomRecord);
        } else {
            DutyScheduleInfo before = dutyScheduleInfoRepository.getById(dutyScheduleInfo.getId());
            if (before.getDDept().equals(dutyScheduleInfo.getDDept())) {
                return;
            } else {
                DutyScheduleSetCustomRecord beforeRecord = dutyScheduleSetCustomRecordRepository.getOne(
                        new LambdaQueryWrapper<DutyScheduleSetCustomRecord>()
                                .eq(DutyScheduleSetCustomRecord::getDeptId, before.getDDept())
                                .eq(DutyScheduleSetCustomRecord::getSType, recordStype)
                        , false);
                beforeRecord.setTotalCount(beforeRecord.getTotalCount() - 1);
                dutyScheduleSetCustomRecord.setTotalCount(dutyScheduleSetCustomRecord.getTotalCount() + 1);
                if (DutyScheduleSetCustomRecordStatusEnum.NOT_PASSED_YET.getValue().equals(dutyScheduleSetCustomRecord.getStatus()) &&
                        dutyScheduleSetCustomRecord.getTotalCount().equals(dutyScheduleSetCustomRecord.getNeedCount())) {
                    dutyScheduleSetCustomRecord.setStatus(DutyScheduleSetCustomRecordStatusEnum.IS_PASSED.getValue());
                }
                dutyScheduleSetCustomRecordRepository.updateById(dutyScheduleSetCustomRecord);
                dutyScheduleSetCustomRecordRepository.updateById(beforeRecord);
            }
        }
    }

    private String getDupostByH4a(String rankCode) {
        String result = "";
        if (rankCode == null) {
            return result;
        }
        switch (rankCode) {
            case "05":
                result = "厅局级正职";
                break;
            case "06":
                result = "厅局级副职";
                break;
            case "07":
                result = "处级人员";
                break;
            case "08":
                result = "处级人员";
                break;
            case "09":
                result = "科长级人员";
                break;
            case "10":
                result = "科长级人员";
                break;
            case "11":
                result = "科员";
                break;
            case "99":
                result = "无行政级别";
                break;
            default:
                return "其他";
        }
        return result;
    }


    @Async
    @Override
    public void doApplyRetry(DutyScheduleInfo dutyScheduleInfo, DutySignInfo info) {
        try {
            RetryUtil.executeWithRetry(new Callable<String>() {
                                           @Override
                                           public String call() throws Exception {
                                               return doApply(dutyScheduleInfo, info);
                                           }
                                       }
                    , 5, 1000, false, null);
        } catch (Exception e) {
            //do nothing
        }
    }

    @Override
    public BaseResult thisTimeUser(String customnName) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime tomorrow = LocalDateTime.now().toLocalDate().plusDays(1l).atStartOfDay();
        DutyScheduleInfoTimeDTO todayDTO = getTimeDTOForDay(customnName, now);
        DutyScheduleInfoTimeDTO tomorrowDTO = getTimeDTOForDay(customnName, tomorrow);
        String todayString = getStringByTimeDTO(todayDTO);
        String tomorrowString = getStringByTimeDTO(tomorrowDTO);
        todayDTO.setTomorrowPerson(tomorrowString);
        todayDTO.setTodayPerson(todayString);
        return BaseResult.ok(todayDTO);
    }


    private String getStringByTimeDTO(DutyScheduleInfoTimeDTO todayDTO) {
        String todayString = "";
        if (todayDTO == null) {
            return "";
        }
        if (todayDTO.getKJInfo() != null) {
            if (todayDTO.getKJInfo().getSType() == null) {
                todayString += todayDTO.getKJInfo().getDUsername();
                return todayString;
            }
            switch (todayDTO.getKJInfo().getSType()) {
                case "1":
                    todayString += todayDTO.getKJInfo().getDUsername();
                    return todayString;
                case "2":
                case "3":
                    todayString += todayDTO.getKJInfo().getDUsername();
                    break;
                default:
                    return "";
            }
        }
        if (todayDTO.getCJInfo() != null) {
            switch (todayDTO.getCJInfo().getSType()) {
                case "1":
                    return "";
                case "2":
                case "3":
                    if (!StringUtils.isEmpty(todayString)) {
                        todayString += todayDTO.getCJInfo().getDUsername();
                    } else {
                        todayString = todayString + "、" + todayDTO.getCJInfo().getDUsername();
                    }
                    break;
                default:
                    return "";
            }
        }
        return todayString;
    }

    private DutyScheduleInfoTimeDTO getTimeDTOForDay(String customnName, LocalDateTime time) {
        log.info("getTimeDTOForDay方法开始,参数1{}，参数二{}", customnName, time);
        LocalDateTime now = time;
        LocalDate today = time.toLocalDate();
        if (systemConfig.getZsCustomName().equals(customnName)) {
            DutyScheduleInfoTimeDTO dutyScheduleInfoTimeDTO = new DutyScheduleInfoTimeDTO();
            DutyScheduleInfo dutyScheduleInfo = dutyScheduleInfoRepository.getOne(new LambdaQueryWrapper<DutyScheduleInfo>()
                    .eq(DutyScheduleInfo::getCustomName, systemConfig.getZsCustomName())
                    .lt(DutyScheduleInfo::getDStartDateTime, time)
                    .ge(DutyScheduleInfo::getDEndDateTime, time)
                    .eq(DutyScheduleInfo::getDutyType, DutyTypeEnum.MASTER_DUTY.getValue()), false);
            if (dutyScheduleInfo == null || dutyScheduleInfo.getDUserno() == null) {
                dutyScheduleInfo = dutyScheduleInfoRepository.getOne(new LambdaQueryWrapper<DutyScheduleInfo>()
                        .eq(DutyScheduleInfo::getCustomName, systemConfig.getZsCustomName())
                        .eq(DutyScheduleInfo::getDDay, today)
                        .eq(DutyScheduleInfo::getDutyType, DutyTypeEnum.MASTER_DUTY.getValue()), false);
            }
            DutyScheduleInfoTimeDetailDTO dutyScheduleInfoTimeDetailDTO = new DutyScheduleInfoTimeDetailDTO();
            if (dutyScheduleInfo != null) {
                BeanUtils.copyProperties(dutyScheduleInfo, dutyScheduleInfoTimeDetailDTO);
            } else {
                dutyScheduleInfoTimeDetailDTO.setDUserno("");
                dutyScheduleInfoTimeDetailDTO.setDUsername("");
            }
            dutyScheduleInfoTimeDTO.setKJInfo(dutyScheduleInfoTimeDetailDTO);
            return dutyScheduleInfoTimeDTO;
        }
        List<DutyScheduleInfo> dutyScheduleInfos = dutyScheduleInfoRepository.list(
                new LambdaQueryWrapper<DutyScheduleInfo>()
                        .eq(DutyScheduleInfo::getCustomName, customnName)
                        .lt(DutyScheduleInfo::getDStartDateTime, time)
                        .ge(DutyScheduleInfo::getDEndDateTime, time)
                        .orderByDesc(DutyScheduleInfo::getDStartDateTime));
        log.info("dutyScheduleInfos{}", dutyScheduleInfos);
        if (CollectionUtils.isEmpty(dutyScheduleInfos)) {
            dutyScheduleInfos = dutyScheduleInfoRepository.list(
                    new LambdaQueryWrapper<DutyScheduleInfo>()
                            .eq(DutyScheduleInfo::getCustomName, customnName)
                            .eq(DutyScheduleInfo::getDDay, today)
                            .orderByDesc(DutyScheduleInfo::getDStartDateTime));
            log.info("dutyScheduleInfos为空,进if判断再查询{}", dutyScheduleInfos);
        }
        DutyScheduleInfoTimeDTO result = new DutyScheduleInfoTimeDTO();
        if (CollectionUtils.isEmpty(dutyScheduleInfos)) {
            log.info("dutyScheduleInfos为空");
        } else {
            log.info("dutyScheduleInfos不为空");
            DutyScheduleInfo current = new DutyScheduleInfo();
            List<DutyScheduleInfo> temp =
                    dutyScheduleInfos.stream().filter(i -> i.getDStartDateTime().compareTo(now) < 0 && i.getDEndDateTime().compareTo(now) > 0).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(temp)) {
                current = temp.get(0);
            }
            //                            }
            if (current.getId() == null) {
                current = dutyScheduleInfos.get(0);
            }

            temp = dutyScheduleInfos.stream()
                    .filter(i -> i.getDStartDateTime().compareTo(now) < 0
                            && i.getDEndDateTime().compareTo(now) > 0).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(temp)) {
                result.setKJInfo(temp.stream().map(i -> {
                    DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                    BeanUtils.copyProperties(i, tempDTO);
                    tempDTO.setFacePath(getPathPath(i));
                    return tempDTO;
                }).filter(i -> "科领导".equals(i.getDUserjob()) || "科员".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                result.setCJInfo(temp.stream().map(i -> {
                    DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                    BeanUtils.copyProperties(i, tempDTO);
                    tempDTO.setFacePath(getPathPath(i));
                    return tempDTO;
                }).filter(i -> "处领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                result.setManagerInfo(temp.stream().map(i -> {
                    DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                    BeanUtils.copyProperties(i, tempDTO);
                    tempDTO.setFacePath(getPathPath(i));
                    return tempDTO;
                }).filter(i -> "关领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
            } else {
                temp = dutyScheduleInfos;
                result.setKJInfo(temp.stream().map(i -> {
                    DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                    BeanUtils.copyProperties(i, tempDTO);
                    tempDTO.setFacePath(getPathPath(i));
                    return tempDTO;
                }).filter(i -> "科领导".equals(i.getDUserjob())|| "科员".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                result.setCJInfo(temp.stream().map(i -> {
                    DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                    BeanUtils.copyProperties(i, tempDTO);
                    tempDTO.setFacePath(getPathPath(i));
                    return tempDTO;
                }).filter(i -> "处领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                result.setManagerInfo(temp.stream().map(i -> {
                    DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                    BeanUtils.copyProperties(i, tempDTO);
                    tempDTO.setFacePath(getPathPath(i));
                    return tempDTO;
                }).filter(i -> "关领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
            }
            return result;
        }
        return result;
    }

    private String getPathPath(DutyScheduleInfo current) {
        if (current == null) {
            return "";
        }
        BasePersonInfo basePersonInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                .eq(BasePersonInfo::getUserno, current.getDUserno()), false);
        if (basePersonInfo == null) {
            return "";
        }
        return basePersonInfo.getFacePath();

    }

    private String
    doApply(DutyScheduleInfo dutyScheduleInfo, DutySignInfo info) throws Exception {
        List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                .eq(BasePersonInfo::getUserno, dutyScheduleInfo.getDUserno()));
        if (!CollectionUtils.isEmpty(basePersonInfos)) {
            BasePersonInfo basePersonInfo = basePersonInfos.get(0);
            JSONObject doApplyJSON = new JSONObject();
            doApplyJSON.put("ApplyType", "1");
            doApplyJSON.put("ApplyUser", dutyScheduleInfo.getDUserno());
            doApplyJSON.put("ApplyName", dutyScheduleInfo.getDUsername());
            doApplyJSON.put("Dept", dutyScheduleInfo.getDDept());
            doApplyJSON.put("DeptName", dutyScheduleInfo.getDDeptname());
            doApplyJSON.put("DutyName", basePersonInfo.getDutypost());
            doApplyJSON.put("Reason", "1");
            doApplyJSON.put("ApplyDate", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            JSONObject dataJSON = new JSONObject();
            ParamDuty paramDuty = guavacacheUtils.getParamDuty(dutyScheduleInfo.getDutyTimesId());
            switch (paramDuty.getDType()) {
                case "1":
                    dataJSON.put("BeginDate", dutyScheduleInfo.getDDay().format(DateTimeFormatter.ISO_DATE) + " 08:30");
                    dataJSON.put("EndDate", dutyScheduleInfo.getDDay().format(DateTimeFormatter.ISO_DATE) + " 12:30");
                    break;
                case "2":
                    dataJSON.put("BeginDate", dutyScheduleInfo.getDDay().format(DateTimeFormatter.ISO_DATE) + " 12:30");
                    dataJSON.put("EndDate", dutyScheduleInfo.getDDay().format(DateTimeFormatter.ISO_DATE) + " 17:30");
                    break;
                case "3":
                    dataJSON.put("BeginDate", dutyScheduleInfo.getDDay().format(DateTimeFormatter.ISO_DATE) + " 17:30");
                    dataJSON.put("EndDate", dutyScheduleInfo.getDDay().plusDays(1l).format(DateTimeFormatter.ISO_DATE) + " 08:30");
                    break;
                case "4":
                    dataJSON.put("BeginDate", dutyScheduleInfo.getDDay().format(DateTimeFormatter.ISO_DATE) + " 08:30");
                    dataJSON.put("EndDate", dutyScheduleInfo.getDDay().format(DateTimeFormatter.ISO_DATE) + " 17:30");
                    break;
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(dataJSON);
            doApplyJSON.put("OverTimeList", jsonArray);
            log.info(doApplyJSON + "|申报入参");
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity requestEntity = new HttpEntity(doApplyJSON, httpHeaders);
            try {
                ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(systemConfig.getDoApplyUrl(), requestEntity, JSONObject.class);
                log.info(responseEntity + "|申报返回");
                //{"code":"0","data":{"applyNo":"JBSQ2022121500004"},"message":"申请成功"}
                JSONObject detailBody = responseEntity.getBody();
                String code = detailBody.getStr("code");
                if ("0".equals(code)) {
                    //成功
                    info.setIsHrSend("1");
                    dutySignInfoRepository.updateById(info);
                } else {
                    //失败
                    log.error("调用申报接口返回失败" + detailBody);
                    throw new Exception("调用申报接口返回失败" + detailBody);
                }
            } catch (Exception e) {
                log.error("调用申报接口异常", e);
                throw e;
            }
//        doApplyJSON.put("duty",dutyScheduleInfo.getDDeptname());
        }
        return "1";
    }

    public DutyScheduleInfoWordVO sort(List<DutyScheduleInfo> list) {
        DutyScheduleInfoWordVO dutyScheduleInfoWordVO = new DutyScheduleInfoWordVO();
        if (!CollectionUtils.isEmpty(list)) {
            dutyScheduleInfoWordVO.setDString(list.get(0).getDDayString());
        }
        List<DutyScheduleInfo> Leader = list.stream().filter((dutyScheduleInfo) -> "关领导".equals(dutyScheduleInfo.getDUserjob())).collect(Collectors.toList());
        log.info("Leader:" + Leader.size());
        List<DutyScheduleInfo> CB = list.stream().filter((dutyScheduleInfo) -> Arrays.asList("07", "08", "处领导").contains(dutyScheduleInfo.getDUserjob())).filter((dutyScheduleInfo) -> StringUtils.isNotBlank(dutyScheduleInfo.getDutyTimesString()) && (dutyScheduleInfo.getDutyTimesString().contains("上午") || dutyScheduleInfo.getDutyTimesString().contains("下午") || dutyScheduleInfo.getDutyTimesString().contains("白天"))).collect(Collectors.toList());
        log.info("CB:" + CB.size());
        List<DutyScheduleInfo> CH = list.stream().filter((dutyScheduleInfo) -> Arrays.asList("07", "08", "处领导").contains(dutyScheduleInfo.getDUserjob())).filter((dutyScheduleInfo) -> StringUtils.isNotBlank(dutyScheduleInfo.getDutyTimesString()) && (dutyScheduleInfo.getDutyTimesString().contains("夜间"))).collect(Collectors.toList());
        log.info("CH:" + CB.size());
        List<DutyScheduleInfo> KB = list.stream().filter((dutyScheduleInfo) -> Arrays.asList("09", "10", "科领导").contains(dutyScheduleInfo.getDUserjob())).filter((dutyScheduleInfo) -> StringUtils.isNotBlank(dutyScheduleInfo.getDutyTimesString()) && (dutyScheduleInfo.getDutyTimesString().contains("上午") || dutyScheduleInfo.getDutyTimesString().contains("下午") || dutyScheduleInfo.getDutyTimesString().contains("白天"))).collect(Collectors.toList());
        log.info("KB:" + CB.size());
        List<DutyScheduleInfo> KH = list.stream().filter((dutyScheduleInfo) -> Arrays.asList("09", "10", "科领导").contains(dutyScheduleInfo.getDUserjob())).filter((dutyScheduleInfo) -> StringUtils.isNotBlank(dutyScheduleInfo.getDutyTimesString()) && (dutyScheduleInfo.getDutyTimesString().contains("夜间"))).collect(Collectors.toList());
        log.info("KH:" + CB.size());
        //拼接 设值
        if (!CollectionUtils.isEmpty(Leader)) {
            AtomicReference<String> dDeptName = new AtomicReference<>("");
            AtomicReference<String> dUserName = new AtomicReference<>("");
            AtomicReference<String> dUserNo = new AtomicReference<>("");
            if (Leader.size() > 1) {
                ArrayList<String> dDeptNames = new ArrayList<>();
                ArrayList<String> dUserNames = new ArrayList<>();
                ArrayList<String> dUserNos = new ArrayList<>();
                for (int i = 0; i < Leader.size(); i++) {
                    if (StringUtils.isNotBlank(Leader.get(i).getDDeptname())) {
                        dDeptNames.add(Leader.get(i).getDDeptname());
                    }
                    if (StringUtils.isNotBlank(Leader.get(i).getDUsername())) {
                        dUserNames.add(Leader.get(i).getDUsername());
                    }
                    if (StringUtils.isNotBlank(Leader.get(i).getDUserno())) {
                        dUserNos.add(Leader.get(i).getDUserno());
                    }
                }
                dDeptName.set(StringUtils.join(dDeptNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserName.set(StringUtils.join(dUserNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserNo.set(StringUtils.join(dUserNos.stream().distinct().collect(Collectors.toList()), ","));
            } else {
                dDeptName.set(Leader.get(0).getDDeptname());
                dUserName.set(Leader.get(0).getDUsername());
                dUserNo.set(Leader.get(0).getDUserno());
            }
            dutyScheduleInfoWordVO.setLeader(dDeptName.get());
            dutyScheduleInfoWordVO.setLeaderName(dUserName.get());
            dutyScheduleInfoWordVO.setLeaderNo(dUserNo.get());
        }
        if (!CollectionUtils.isEmpty(CB)) {
            AtomicReference<String> dDeptName = new AtomicReference<>("");
            AtomicReference<String> dUserName = new AtomicReference<>("");
            AtomicReference<String> dUserNo = new AtomicReference<>("");
            if (CB.size() > 1) {
                ArrayList<String> dDeptNames = new ArrayList<>();
                ArrayList<String> dUserNames = new ArrayList<>();
                ArrayList<String> dUserNos = new ArrayList<>();
                for (int i = 0; i < CB.size(); i++) {
                    if (StringUtils.isNotBlank(CB.get(i).getDDeptname())) {
                        dDeptNames.add(CB.get(i).getDDeptname());
                        //dDeptName.set(dDeptName.get()+CB.get(i).getDDeptname()+",");
                    }
                    if (StringUtils.isNotBlank(CB.get(i).getDUsername())) {
                        dUserNames.add(CB.get(i).getDUsername());
                        //dUserName.set(dUserName.get()+CB.get(i).getDUsername()+",");
                    }
                    if (StringUtils.isNotBlank(CB.get(i).getPhoneShort())) {
                        dUserNos.add(CB.get(i).getPhoneShort());
                        //dUserNo.set(dUserNo.get()+CB.get(i).getDUserno()+",");
                    }
//                    if (i==CB.size()-1){
//                        dDeptName.set(dDeptName.get()+CB.get(i).getDDeptname());
//                        dUserName.set(dUserName.get()+CB.get(i).getDUsername());
//                        dUserNo.set(dUserNo.get()+CB.get(i).getDUserno());
//                    }
                }
                dDeptName.set(StringUtils.join(dDeptNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserName.set(StringUtils.join(dUserNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserNo.set(StringUtils.join(dUserNos.stream().distinct().collect(Collectors.toList()), ","));
            } else {
                dDeptName.set(CB.get(0).getDDeptname());
                dUserName.set(CB.get(0).getDUsername());
                dUserNo.set(CB.get(0).getPhoneShort());
            }
            dutyScheduleInfoWordVO.setCBdeptName(dDeptName.get());
            dutyScheduleInfoWordVO.setCBpersonName(dUserName.get());
            dutyScheduleInfoWordVO.setCBpersonNo(dUserNo.get());
        }

        if (!CollectionUtils.isEmpty(CH)) {
            AtomicReference<String> dDeptName = new AtomicReference<>("");
            AtomicReference<String> dUserName = new AtomicReference<>("");
            AtomicReference<String> dUserNo = new AtomicReference<>("");
            if (CH.size() > 1) {
                ArrayList<String> dDeptNames = new ArrayList<>();
                ArrayList<String> dUserNames = new ArrayList<>();
                ArrayList<String> dUserNos = new ArrayList<>();
                for (int i = 0; i < CH.size(); i++) {
                    if (StringUtils.isNotBlank(CH.get(i).getDDeptname())) {
                        dDeptNames.add(CH.get(i).getDDeptname());
                        //dDeptName.set(dDeptName.get()+CH.get(i).getDDeptname()+",");
                    }
                    if (StringUtils.isNotBlank(CH.get(i).getDUsername())) {
                        dUserNames.add(CH.get(i).getDUsername());
                        //dUserName.set(dUserName.get()+CH.get(i).getDUsername()+",");
                    }
                    if (StringUtils.isNotBlank(CH.get(i).getDUsername())) {
                        dUserNos.add(CH.get(i).getDUsername());
                        //dUserNo.set(dUserNo.get()+CH.get(i).getDUserno()+",");
                    }

                }
                dDeptName.set(StringUtils.join(dDeptNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserName.set(StringUtils.join(dUserNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserNo.set(StringUtils.join(dUserNos.stream().distinct().collect(Collectors.toList()), ","));
            } else {
                dDeptName.set(CH.get(0).getDDeptname());
                dUserName.set(CH.get(0).getDUsername());
                dUserNo.set(CH.get(0).getPhoneShort());
            }
            dutyScheduleInfoWordVO.setCHdeptName(dDeptName.get());
            dutyScheduleInfoWordVO.setCHpersonName(dUserName.get());
            dutyScheduleInfoWordVO.setCHpersonNo(dUserNo.get());
        }

        if (!CollectionUtils.isEmpty(KB)) {
            AtomicReference<String> dDeptName = new AtomicReference<>("");
            AtomicReference<String> dUserName = new AtomicReference<>("");
            AtomicReference<String> dUserNo = new AtomicReference<>("");
            if (KB.size() > 1) {
                ArrayList<String> dDeptNames = new ArrayList<>();
                ArrayList<String> dUserNames = new ArrayList<>();
                ArrayList<String> dUserNos = new ArrayList<>();
                for (int i = 0; i < KB.size(); i++) {
                    if (StringUtils.isNotBlank(KB.get(i).getDDeptname())) {
                        dDeptNames.add(KB.get(i).getDDeptname());
                        //dDeptName.set(dDeptName.get()+KB.get(i).getDDeptname()+",");
                    }
                    if (StringUtils.isNotBlank(KB.get(i).getDUsername())) {
                        dUserNames.add(KB.get(i).getDUsername());
                        //dUserName.set(dUserName.get()+KB.get(i).getDUsername()+",");
                    }
                    if (StringUtils.isNotBlank(KB.get(i).getDUserno())) {
                        dUserNos.add(KB.get(i).getDUserno());
                        //dUserNo.set(dUserNo.get()+KB.get(i).getDUserno()+",");
                    }
//                    if (i==KB.size()-1){
//                        dDeptName.set(dDeptName.get()+KB.get(i).getDDeptname());
//                        dUserName.set(dUserName.get()+KB.get(i).getDUsername());
//                        dUserNo.set(dUserNo.get()+KB.get(i).getDUserno());
//                    }
                }
                dDeptName.set(StringUtils.join(dDeptNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserName.set(StringUtils.join(dUserNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserNo.set(StringUtils.join(dUserNos.stream().distinct().collect(Collectors.toList()), ","));
            } else {
                dDeptName.set(KB.get(0).getDDeptname());
                dUserName.set(KB.get(0).getDUsername());
                dUserNo.set(KB.get(0).getPhoneShort());
            }

            dutyScheduleInfoWordVO.setKBdeptName(dDeptName.get());
            dutyScheduleInfoWordVO.setKBpersonName(dUserName.get());
            dutyScheduleInfoWordVO.setKBpersonNo(dUserNo.get());
        }

        if (!CollectionUtils.isEmpty(KH)) {
            AtomicReference<String> dDeptName = new AtomicReference<>("");
            AtomicReference<String> dUserName = new AtomicReference<>("");
            AtomicReference<String> dUserNo = new AtomicReference<>("");
            if (KH.size() > 1) {
                ArrayList<String> dDeptNames = new ArrayList<>();
                ArrayList<String> dUserNames = new ArrayList<>();
                ArrayList<String> dUserNos = new ArrayList<>();
                for (int i = 0; i < KH.size(); i++) {
                    if (StringUtils.isNotBlank(KH.get(i).getDDeptname())) {
                        dDeptNames.add(KH.get(i).getDDeptname());
                        //dDeptName.set(dDeptName.get()+KH.get(i).getDDeptname()+",");
                    }
                    if (StringUtils.isNotBlank(KH.get(i).getDUsername())) {
                        dUserNames.add(KH.get(i).getDUsername());
                        //dUserName.set(dUserName.get()+KH.get(i).getDUsername()+",");
                    }
                    if (StringUtils.isNotBlank(KH.get(i).getDUserno())) {
                        dUserNos.add(KH.get(i).getDUserno());
                    }
//                    if (i==KH.size()-1){
//                        dDeptName.set(dDeptName.get()+KH.get(i).getDDeptname());
//                        dUserName.set(dUserName.get()+KH.get(i).getDUsername());
//                        dUserNo.set(dUserNo.get()+KH.get(i).getDUserno());
//                    }
                }
                dDeptName.set(StringUtils.join(dDeptNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserName.set(StringUtils.join(dUserNames.stream().distinct().collect(Collectors.toList()), ","));
                dUserNo.set(StringUtils.join(dUserNos.stream().distinct().collect(Collectors.toList()), ","));
            } else {
                dDeptName.set(KH.get(0).getDDeptname());
                dUserName.set(KH.get(0).getDUsername());
                dUserNo.set(KH.get(0).getPhoneShort());
            }

            dutyScheduleInfoWordVO.setKHdeptName(dDeptName.get());
            dutyScheduleInfoWordVO.setKHpersonName(dUserName.get());
            dutyScheduleInfoWordVO.setKHpersonNo(dUserNo.get());
        }

        return dutyScheduleInfoWordVO;
    }

    public MoneyVO getdutyTimesString(DutyScheduleInfo scheduleInfo) {
        if (!StringUtils.isEmpty(scheduleInfo.getDUserno())) {
            MoneyVO moneyVO = new MoneyVO();
            DayOfWeek dayOfWeek = scheduleInfo.getDDay().getDayOfWeek();
            String dtype = dutyScheduleInfoRepository.getDtype(scheduleInfo);//时段
            log.info("============scheduleInfo:" + scheduleInfo);
            log.info("============dtype:" + dtype);
            ParamDuty paramDuty = paramDutyRepository.getOne(new LambdaQueryWrapper<ParamDuty>()
                    .eq(ParamDuty::getDType, dtype)
                    .eq(ParamDuty::getDDept, scheduleInfo.getCustomId()));
            log.info("============paramDuty:" + paramDuty);
            String subsidy;
            if (paramDuty != null) {
                ParamSubsidy paramSubsidy;
                if (SubsiduEnum.TYPE_WB.getValue().equals(scheduleInfo.getSType())) {
                    // stype为1 分为工作日和周末 周末为4  工作日为1
                    if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
                        paramSubsidy = paramSubsidyRepository.getOne(new LambdaQueryWrapper<ParamSubsidy>()
                                .eq(ParamSubsidy::getParamDutyId, paramDuty.getId())
                                .eq(ParamSubsidy::getSType, SubsiduEnum.TYPE_ZM.getValue()));
                    } else {
                        paramSubsidy = paramSubsidyRepository.getOne(new LambdaQueryWrapper<ParamSubsidy>()
                                .eq(ParamSubsidy::getParamDutyId, paramDuty.getId())
                                .eq(ParamSubsidy::getSType, SubsiduEnum.TYPE_WB.getValue()));
                    }
                } else {
                    paramSubsidy = paramSubsidyRepository.getOne(new LambdaQueryWrapper<ParamSubsidy>()
                            .eq(ParamSubsidy::getParamDutyId, paramDuty.getId())
                            .eq(ParamSubsidy::getSType, scheduleInfo.getSType()));
                }
                log.info("paramSubsidy{}", paramSubsidy);
                if (paramSubsidy != null) {
                    subsidy = paramSubsidy.getSubsidy().toString();
                } else {
                    subsidy = "未设置补贴标准";
                }
            } else {
                subsidy = "未设置补贴标准";
            }

            moneyVO.setSubsidy(subsidy);
            moneyVO.setTotalsubsidy(subsidy);
            //日常和双休
            if (STypeEnum.TYPE_WB.getValue().equals(scheduleInfo.getSType())) {
                //双休
                if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
                    //双休
                    if (DTypeEnum.TYPE_MORNING.getValue().equals(dtype) || DTypeEnum.TYPE_AFTERNOON.getValue().equals(dtype) || DTypeEnum.TYPE_EVENING.getValue().equals(dtype)) {
                        for (DTypeEnum dTypeEnum : DTypeEnum.values()) {
                            if (dTypeEnum.getValue().equals(dtype) && !dtype.equals(DTypeEnum.TYPE_EVENING.getValue())) {
                                moneyVO.setTimesString("双休日" + dTypeEnum.getDescription() + "班");
                            }
                            if (dtype.equals(DTypeEnum.TYPE_EVENING.getValue())) {
                                moneyVO.setTimesString("双休日" + DTypeEnum.TYPE_EVENING.getDescription() + "班");
                                moneyVO.setSubsidy(subsidy);
                                moneyVO.setTotalsubsidy(subsidy);
                            }
                        }
                    }
                } else {
                    //日常晚
                    moneyVO.setTimesString("日常晚班");
                    moneyVO.setSubsidy(subsidy);
                    moneyVO.setTotalsubsidy(subsidy);
                }
            } else if (STypeEnum.TYPE_ZMB.getValue().equals(scheduleInfo.getSType())) { //节假日
                //节假日300rmd
                for (DTypeEnum dTypeEnum : DTypeEnum.values()) {
                    if (dTypeEnum.getValue().equals(dtype)) {
                        moneyVO.setTimesString("节假日" + dTypeEnum.getDescription() + "班");
                        moneyVO.setSubsidy(subsidy);
                        moneyVO.setTotalsubsidy(subsidy);
                    }
                }
            } else {
                for (DTypeEnum dTypeEnum : DTypeEnum.values()) {
                    if (dTypeEnum.getValue().equals(dtype)) {
                        moneyVO.setTimesString("重要日" + dTypeEnum.getDescription() + "班");
                        moneyVO.setSubsidy(subsidy);
                        moneyVO.setTotalsubsidy(subsidy);
                    }
                }
            }
            return moneyVO;
        }
        return null;
    }

    private DutyScheduleInfoTimeDTO getTimeDTOForNow(String customnName, LocalDateTime time) {
        return getTimeDTOForDay(customnName, time);
    }


    private DutyScheduleInfoTimeDTO getTimeDTOForNow(String customnName, LocalDateTime time, Map<String, ScreenDutyMaps> screenDutyMapsMap, List<DutyScheduleInfo> dutyScheduleInfos) {
        ScreenDutyMaps custom = screenDutyMapsMap.get(customnName);
        if (custom == null) {
            return new DutyScheduleInfoTimeDTO();
        }
        LocalDateTime now = time;
        LocalDate today = time.toLocalDate();
        LocalDate yesterday = time.toLocalDate().minusDays(1l);
        if (systemConfig.getZsCustomName().equals(customnName)) {
//            if (!CollectionUtils.isEmpty(dutyScheduleInfos)){
            DutyScheduleInfoTimeDTO dutyScheduleInfoTimeDTO = new DutyScheduleInfoTimeDTO();
//            DutyScheduleInfoTimeDetailDTO dutyScheduleInfoTimeDetailDTO =
            DutyScheduleInfo dutyScheduleInfo = dutyScheduleInfoRepository.getOne(new LambdaQueryWrapper<DutyScheduleInfo>()
                    .eq(DutyScheduleInfo::getCustomName, systemConfig.getZsCustomName())
                    .eq(DutyScheduleInfo::getDDay, time.toLocalDate())
                    .eq(DutyScheduleInfo::getDutyType, "3"), false);
//                dutyScheduleInfoTimeDetailDTO.set
            DutyScheduleInfoTimeDetailDTO dutyScheduleInfoTimeDetailDTO = new DutyScheduleInfoTimeDetailDTO();
            if (dutyScheduleInfo != null) {
                BeanUtils.copyProperties(dutyScheduleInfo, dutyScheduleInfoTimeDetailDTO);
            } else {
                dutyScheduleInfoTimeDetailDTO.setDUserno("");
                dutyScheduleInfoTimeDetailDTO.setDUsername("");
            }
            dutyScheduleInfoTimeDTO.setKJInfo(dutyScheduleInfoTimeDetailDTO);
            return dutyScheduleInfoTimeDTO;
//            }
        }
        DutyScheduleInfoTimeDTO result = new DutyScheduleInfoTimeDTO();
        if (CollectionUtils.isEmpty(dutyScheduleInfos)) {
            ParamLeader GLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                    .eq(ParamLeader::getDeptId, custom.getId())
                    .eq(ParamLeader::getLeaderName, "1"));
            ParamLeader CLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                    .eq(ParamLeader::getDeptId, custom.getId())
                    .eq(ParamLeader::getLeaderName, "2"));
            if (GLeader != null) {
                DutyScheduleInfoTimeDetailDTO managerInfo = new DutyScheduleInfoTimeDetailDTO();
                BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(GLeader.getDeptId());
                List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno, GLeader.getLeaderCode()));
                if (baseDeptInfo != null && !CollectionUtils.isEmpty(basePersonInfos)) {
                    BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                    managerInfo.setDDeptname(baseDeptInfo.getDeptName());
                    managerInfo.setDPhone(basePersonInfo.getPhone());
                    managerInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                    managerInfo.setDPhoneLand(basePersonInfo.getPhoneLand());
                    managerInfo.setDUsername(basePersonInfo.getUsername());
                    managerInfo.setDType("2");
                    managerInfo.setSType("1");
                    managerInfo.setDUserno(basePersonInfo.getUserno());
                    managerInfo.setDUserjob("关领导");
                    managerInfo.setDutypost(getDupostByH4a(basePersonInfo.getRealRackCode()));
                    managerInfo.setRankCode(basePersonInfo.getRankCode());
                    managerInfo.setFacePath(basePersonInfo.getFacePath());
                }
                result.setManagerInfo(managerInfo);
            }
            if (CLeader != null) {
                DutyScheduleInfoTimeDetailDTO CJInfo = new DutyScheduleInfoTimeDetailDTO();
                BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(CLeader.getDeptId());
                List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                        .eq(BasePersonInfo::getUserno, CLeader.getLeaderCode()));
                if (baseDeptInfo != null && !CollectionUtils.isEmpty(basePersonInfos)) {
                    BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                    CJInfo.setDDeptname(baseDeptInfo.getDeptName());
                    CJInfo.setDPhone(basePersonInfo.getPhone());
                    CJInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                    CJInfo.setDPhoneLand(basePersonInfo.getPhoneLand());
                    CJInfo.setDUsername(basePersonInfo.getUsername());
                    CJInfo.setDType("2");
                    //--------
                    CJInfo.setSType("2");
                    CJInfo.setDUserno(basePersonInfo.getUserno());
                    CJInfo.setDUserjob("处领导");
                    CJInfo.setDutypost(getDupostByH4a(basePersonInfo.getRealRackCode()));
                    CJInfo.setRankCode(basePersonInfo.getRankCode());
                    CJInfo.setFacePath(basePersonInfo.getFacePath());
                }
                result.setCJInfo(CJInfo);
            }
            return result;
        } else {
            DutyScheduleInfo dutyScheduleInfo = getSignInTaragetScheduleInfo(dutyScheduleInfos, now);
            DutyScheduleInfo current = new DutyScheduleInfo();
            switch (dutyScheduleInfo.getSType()) {
                case "1":
                    DayOfWeek day = DayOfWeek.of(today.get(ChronoField.DAY_OF_WEEK));
                    switch (day) {
                        case SATURDAY:
                        case SUNDAY:
                            List<DutyScheduleInfo> temp = dutyScheduleInfos.stream()
                                    .filter(i -> i.getDStartDateTime().compareTo(now) < 0
                                            && i.getDEndDateTime().compareTo(now) > 0).collect(Collectors.toList());
                            if (!CollectionUtils.isEmpty(temp)) {
                                current = temp.get(0);
                            }
                            if (current.getId() == null) {
                                current = dutyScheduleInfos.get(0);
                            }
                            break;
                        default:
                            temp = dutyScheduleInfos.stream()
                                    .filter(i -> i.getDutyTimesString().contains("夜间")).collect(Collectors.toList());
                            if (!CollectionUtils.isEmpty(temp)) {
                                current = temp.get(0);
                            }
                            if (current.getId() == null) {
                                current = dutyScheduleInfos.get(0);
                            }
                    }
                    DutyScheduleInfoTimeDetailDTO currentTimeDetailDTO = new DutyScheduleInfoTimeDetailDTO();
                    BeanUtils.copyProperties(current, currentTimeDetailDTO);
                    currentTimeDetailDTO.setFacePath(getPathPath(current));
                    result.setKJInfo(currentTimeDetailDTO);
                    ParamLeader GLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                            .eq(ParamLeader::getDeptId, custom.getId())
                            .eq(ParamLeader::getLeaderName, "1"));
                    ParamLeader CLeader = paramLeaderRepository.getOne(new LambdaQueryWrapper<ParamLeader>()
                            .eq(ParamLeader::getDeptId, custom.getId())
                            .eq(ParamLeader::getLeaderName, "2"));
                    if (GLeader != null) {
                        DutyScheduleInfoTimeDetailDTO managerInfo = new DutyScheduleInfoTimeDetailDTO();
                        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(GLeader.getDeptId());
                        List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                                .eq(BasePersonInfo::getUserno, GLeader.getLeaderCode()));
                        if (baseDeptInfo != null && !CollectionUtils.isEmpty(basePersonInfos)) {
                            BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                            managerInfo.setDDeptname(baseDeptInfo.getDeptName());
                            managerInfo.setDPhone(basePersonInfo.getPhone());
                            managerInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                            managerInfo.setDPhoneLand(basePersonInfo.getPhoneLand());
                            managerInfo.setDUsername(basePersonInfo.getUsername());
                            managerInfo.setDType("2");
                            managerInfo.setSType("1");
                            managerInfo.setDUserno(basePersonInfo.getUserno());
                            managerInfo.setDUserjob("关领导");
                            managerInfo.setDutypost(getDupostByH4a(basePersonInfo.getRealRackCode()));
                            managerInfo.setRankCode(basePersonInfo.getRankCode());
                            managerInfo.setFacePath(basePersonInfo.getFacePath());
                        }
                        result.setManagerInfo(managerInfo);
                    }
                    if (CLeader != null) {
                        DutyScheduleInfoTimeDetailDTO CJInfo = new DutyScheduleInfoTimeDetailDTO();
                        BaseDeptInfo baseDeptInfo = baseDeptInfoRepository.getById(CLeader.getDeptId());
                        List<BasePersonInfo> basePersonInfos = basePersonInfoRepository.list(new LambdaQueryWrapper<BasePersonInfo>()
                                .eq(BasePersonInfo::getUserno, CLeader.getLeaderCode()));
                        if (baseDeptInfo != null && !CollectionUtils.isEmpty(basePersonInfos)) {
                            BasePersonInfo basePersonInfo = basePersonInfos.get(0);
                            CJInfo.setDDeptname(baseDeptInfo.getDeptName());
                            CJInfo.setDPhone(basePersonInfo.getPhone());
                            CJInfo.setPhoneShort(basePersonInfo.getPhoneShort());
                            CJInfo.setDPhoneLand(basePersonInfo.getPhoneLand());
                            CJInfo.setDUsername(basePersonInfo.getUsername());
                            CJInfo.setDType("2");
                            CJInfo.setSType("2");
                            CJInfo.setDUserno(basePersonInfo.getUserno());
                            CJInfo.setDUserjob("处领导");
                            CJInfo.setDutypost(getDupostByH4a(basePersonInfo.getRealRackCode()));
                            CJInfo.setRankCode(basePersonInfo.getRankCode());
                            CJInfo.setFacePath(basePersonInfo.getFacePath());
                        }
                        result.setCJInfo(CJInfo);
                    }
                    return result;
                case "2":
                case "3":
                    List<DutyScheduleInfo> temp = dutyScheduleInfos.stream()
                            .filter(i -> i.getDStartDateTime().compareTo(now) < 0
                                    && i.getDEndDateTime().compareTo(now) > 0).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(temp)) {
                        result.setKJInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "科领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setCJInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "处领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setKJInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "关领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                    } else {
                        temp = dutyScheduleInfos;
                        result.setKJInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "科领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setCJInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "处领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                        result.setManagerInfo(temp.stream().map(i -> {
                            DutyScheduleInfoTimeDetailDTO tempDTO = new DutyScheduleInfoTimeDetailDTO();
                            BeanUtils.copyProperties(i, tempDTO);
                            tempDTO.setFacePath(getPathPath(i));
                            return tempDTO;
                        }).filter(i -> "关领导".equals(i.getDUserjob())).max((a, b) -> a.getCreateTime().compareTo(b.getCreateTime())).orElse(null));
                    }
                    return result;

                default:
                    return null;
            }
        }
    }

    private DutyScheduleInfo getSignInTaragetScheduleInfo(List<DutyScheduleInfo> dutyScheduleInfos, LocalDateTime now) {
        for (DutyScheduleInfo dutyScheduleInfo : dutyScheduleInfos) {
            ParamDuty paramDuty = guavacacheUtils.getParamDuty(dutyScheduleInfo.getDutyTimesId());
            if (paramDuty != null && !StringUtils.isEmpty(paramDuty.getId())) {
                LocalTime startTime = paramDuty.getDStartTime();
                LocalTime endTime = paramDuty.getDEndTime();
                LocalDateTime startDateTime;
                LocalDateTime endDateTime;
                startDateTime = dutyScheduleInfo.getDDay().atTime(startTime);
                if (now.compareTo(startDateTime) > 0) {
                    return dutyScheduleInfo;
                }
            }
        }
        return dutyScheduleInfos.get(0);
    }
}
